for loop answer不会停止重复

时间:2017-10-04 00:20:20

标签: python python-3.x

我有这个程序:

print('~Find and Replace~\n')

phrase = input('Enter a phrase:')
find = input('Enter a letter to find:')
end = input('Enter a letter to replace:')

for j in phrase:
    j = phrase.count(find)
    print(j)

它出现了这样:

~Find and Replace~

Enter a phrase:pythop
Enter a letter to find:p
Enter a letter to replace:x
2
2
2
2
2
2

我应该怎么做才能使用for循环只打印一次?

2 个答案:

答案 0 :(得分:5)

摆脱for循环。你为什么拥有它? (你想重复什么?)

print('~Find and Replace~\n')

phrase = input('Enter a phrase:')
find = input('Enter a letter to find:')
end = input('Enter a letter to replace:')

j = phrase.count(find)
print(j)

答案 1 :(得分:3)

如果要替换字符串中的字母,请使用str.replace()功能。不需要for循环。

phrase = input('Enter a phrase:')
find = input('Enter a letter to find:')
end = input('Enter a letter to replace:')

print(phrase.replace(find, end))