0

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

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
4

1 回答 1

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.

于 2013-10-31T23:25:01.883 回答