我有这个程序:
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循环只打印一次?
答案 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))