WildCat
WildCat

Reputation: 19

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

Upvotes: 0

Views: 140

Answers (1)

abarnert
abarnert

Reputation: 365717

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.

Upvotes: 1

Related Questions