2016-02-02 59 views
0

下面的代碼顯示「字」的位置,如果它在字符串中出現一次。如何更改我的代碼,以便如果「字」在字符串中出現多次,它將打印所有位置?如何在字符串中找到多於一個子字符串的位置(Python 3.4.3 shell)

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

*您 –

+0

實際上它是在列表中的位置,因爲你是用文字 – tinySandy

回答

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) 
+0

分割字符串成一個列表完善!謝謝 – Zoe

3

使用enumerate

[i for i, w in enumerate(s.split()) if w == 'test'] 

例子:

s = 'test test something something test' 

輸出:

[0, 1, 4] 

,但我想這不是你在找什麼,如果你需要啓動工作指數DS在一個字符串我會建議使用re.finditer

import re 

[w.start() for w in re.finditer('test', s)] 

和輸出爲同一s是:

[0, 5, 30] 
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 
相關問題