简体   繁体   中英

Replacing words in a string- but with two different words: Python3

Trying to get it so that it takes input the same number of times the certain word appears in the original string and replaces it with each word that was the input.

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

The problem is that, each time through the loop, you create a whole new new_line , ignoring the previous new_line and just going back to the original replaced . So, only the last replacement will be visible when the loop is done.

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

So, the second replacement ignores the first one.

What you want to do is this:

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)

A simplified example of the same problem might be easier to understand:

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

This will just print 4 . But now:

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

This will print 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM