[英]How do i find the position of MORE THAN ONE substring in a string (Python 3.4.3 shell)
如果字符串中出現一次,則以下代碼顯示“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))
使用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]
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)
另一種不會在空間上分裂的解決方案。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.