Python 2.7 为什么python为字符串中的相同字符显示相同的索引值?
我正在尝试打印字符串“python程序”中出现的所有字符“p”。它在字符串中显示与0相同的索引值“p”,而不是0和7Python 2.7 为什么python为字符串中的相同字符显示相同的索引值?,python-2.7,Python 2.7,我正在尝试打印字符串“python程序”中出现的所有字符“p”。它在字符串中显示与0相同的索引值“p”,而不是0和7 str = raw_input("enter a string:") sub = raw_input("enter a sub string:") for i in str: if i.lower() == sub.lower(): print i, str.index(i) 输出: enter a string:python program enter
str = raw_input("enter a string:")
sub = raw_input("enter a sub string:")
for i in str:
if i.lower() == sub.lower():
print i, str.index(i)
输出:
enter a string:python program
enter a sub string:p
p 0
p 0
输入字符串:python程序
输入子字符串:p
P0
P0
以下是解决方案的建议:
sub = raw_input("enter the sub string you're looking for: ")
string = raw_input("enter the text you're looking in: ")
def get_next(text, sub):
for i in range(len(text)+1):
pos = text.find(sub, i)
if pos == -1 : #if no occurrences, do nothing
break
if i == pos: #would print the sub and the pos only if pointer in correct position
print sub, pos
get_next(string, sub)
你可以用while循环代替函数,但我认为如果你想多次使用代码,函数会更方便。
str.index(I)
的意思是“在str
中出现的I
的第一个索引是什么?”。如果使用相同的参数调用它,如何返回不同的值?你应该改为使用for你的for
循环。因此你调用str.index(i)
,其中i
等于“p”
两次。为什么你认为它会给出两种不同的结果呢。。明白了。但是我不能用enumerate写同样的东西。