如何在字符串中找到多于一个子字符串的位置(Python 3.4.3 shell) [英] How do i find the position of MORE THAN ONE substring in a string (Python 3.4.3 shell)

查看:581
本文介绍了如何在字符串中找到多于一个子字符串的位置(Python 3.4.3 shell)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果字符串中出现一次,则以下代码显示word的位置。如何更改我的代码,以便如果字在字符串中出现多次,它将打印所有位置?

The following code displays the position of "word" if it appears once in the string. How can i change my code so that if the "word" appears more than once in the string, it will print all positions?

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


推荐答案

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)

这篇关于如何在字符串中找到多于一个子字符串的位置(Python 3.4.3 shell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆