替换字符串中的单词 - 但有两个不同的单词:Python3

时间:2013-10-31 23:13:47

标签: python string loops python-3.x

尝试获取它,使得输入与原始字符串中出现的特定单词的次数相同,并将其替换为输入的每个单词。

def replace_parts_of_speech (replaced, part_of_speech):
    '''Finds and replaces parts of speech with words '''
    new_line=''

    for i in range (replaced.count(part_of_speech)):
        new=input('Enter '+ part_of_speech +':') 
        new_line = replaced.replace(part_of_speech,new,1)


    return new_line

1 个答案:

答案 0 :(得分:1)

问题在于,每次循环播放时,您都会创建一个全新的new_line,忽略之前的new_line,然后返回到原来的replaced。因此,循环完成后,只有最后一个替换才会可见。

for i in range (replaced.count(part_of_speech)):
    new=input('Enter '+ part_of_speech +':') 
    new_line = replaced.replace(part_of_speech,new,1)

所以,第二个替换忽略了第一个。

你想要做的是:

new_line = replaced
for i in range (replaced.count(part_of_speech)):
    new=input('Enter '+ part_of_speech +':') 
    new_line = new_line.replace(part_of_speech,new,1)

同一问题的简化示例可能更容易理解:

start = 0
current = 0
for i in range(5):
    current = start + i
print(current)

这将只打印4。但现在:

start = 0
current = start
for i in range(5):
    current = current + i
print(current)

这将打印10