如果字符串中出现一次,则以下代码显示“word”的位置。如何更改我的代码,以便如果“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))
答案 0 :(得分:3)
使用enumerate
:
[i for i, w in enumerate(s.split()) if w == 'test']
示例:
s = 'test test something something test'
输出:
[0, 1, 4]
但我想这不是你想要的,如果你需要为字符串中的单词开始索引我建议使用re.finditer
:
import re
[w.start() for w in re.finditer('test', s)]
同一s
的输出将是:
[0, 5, 30]
答案 1 :(得分:0)
sentence = input("Please input a sentence: ")
word = input("Please input a word: ")
sentence = sentence.lower()
word = word.lower()
wordlist = sentence.split(' ')
print ("Your word '%s' is in these positions:" % word)
for position,w in enumerate(wordlist):
if w == word:
print("%d" % position + 1)
答案 2 :(得分:0)
另一种不会在空间上分裂的解决方案。
def multipos(string, pattern):
res = []
count = 0
while True:
pos = string.find(pattern)
if pos == -1:
break
else:
res += [pos+count]
count += pos+1
string = string[pos+1:]
return res
test = "aaaa 123 bbbb 123 cccc 123"
res = multipos("aaaa 123 bbbb 123 cccc 123", "123")
print res
for a in res:
print test[a:a+3]
脚本输出:
% python multipos.py
[5, 14, 23]
123
123
123