以下代码显示“word”在字符串中出现一次的位置。我如何更改我的代码,以便如果“单词”在字符串中出现多次,它将打印所有位置?
string = input("Please input a sentence: ")
word = input("Please input a word: ")
string.lower()
word.lower()
list1 = string.split(' ')
position = list1.index(word)
location = (position+1)
print("You're word, {0}, is in position {1}".format (word, location))
Use enumerate https://docs.python.org/3.4/library/functions.html#enumerate:
[i for i, w in enumerate(s.split()) if w == 'test']
Example:
s = 'test test something something test'
Output:
[0, 1, 4]
但我想这不是您正在寻找的,如果您需要字符串中单词的起始索引,我建议使用re.finditer https://docs.python.org/3/library/re.html#re.finditer:
import re
[w.start() for w in re.finditer('test', s)]
和相同的输出s
将会:
[0, 5, 30]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)