0
How do I find the position of other strings in Python?
what I need: ['m', 'f', 'm', 'f', 'f'] [2, 4, 5] I know I need looping for this, but I still don't get how I am going to get all of them. If someone want to help me, I need a program to find these positions in any case. q = int(input('How many people there are? ')) for c in range(1, q + 1): str(input(f'Enter sex of {c}th person [M/F]: ')).lower().strip()[0] If someone help me with this, I would be really grateful for that!
3 Respostas
0
so..correct me if i'm wrong:-
['m', 'f', 'm', 'f', 'f'] ....is your input..
[2, 4, 5]...is your output...
....if so...then try this...
m_or_f = ['m', 'f', 'm', 'f', 'f']
pos = [x+1 for x, y in enumerate(m_or_f) if y == 'f']
or
pos = [x for x, y in enumerate(m_or_f, 1) if y == 'f']
print(pos)
print(pos)
+ 4
ok, i made some slightly changes to your code, so you are able now to get all inputs and store them in a list.
To find the position of a substring in an other string, you can use index. index can only find the first occurance of the string you are searching for, but you can use start and end parameter to get more than one occurannce.
An other possible way is to use regex. Here you can find all occurances of a search string in a single run.
But this use of index or whatever needs some more explanation from your side.
Here is the reworked code for you:
q = int(input('How many people there are? '))
inp = []
for c in range(1, q + 1):
inp.append(input(f'Enter sex of {c}th person [M/F]: ').lower().strip())
print(inp)
0
To get all the indexes of a string or a list with a loop you could use the index method. example:
s = “abcdef”
for i in s:
print(i,”is in index:”,s.index(i))
output would be:
a is in index 0
b is in index 1
... and so on.
Hope this helps and is what you were asking for!