问题
I guess the heading is self-explanatory, still, I'll make myself more clear.
I've to find the indexes of every occurrence of a character in a string. For example,
word = "banana"
def indexes(x, word):
#some code
return (list of indexes of x character in the word)
output:
indexes('a', word)
>> [1, 3, 5]
How do I get this result?
回答1:
Try this:
word = "banana"
def indexes(x, word):
output = []
for i,y in enumerate(word):
if x == y:
output.append(i)
return output
output = indexes("a", word)
print(output)
回答2:
Using list comprehension
- enumerate() - method adds a counter to an iterable and returns it in a form of enumerate object.
Ex.
word = "banana"
indexes = [ index for index,x in enumerate(word) if x in 'a' ]
print(indexes)
O/P:
[1, 3, 5]
回答3:
i would do something like this
word = "banana"
def indexes(x, word):
result = []
for idx, letter in enumerate(word):
if letter == x:
result.append(idx)
return result
and then
indexes('a', word)
[1, 3, 5]
来源:https://stackoverflow.com/questions/57309688/how-to-find-the-indexes-of-all-occerences-of-a-character-in-a-string