Python Forum

Full Version: str.replace affects the if statement!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have two codes where using str.replace affects the performance of the if statement it lies in.
Can anyone tell me why this difference happens!!
Code#1
from random import randint
sen="I am a NOUN, and I'll always be NOUNing around, and all the NOUNs are gonna hate it"
i=0
while i<len(sen):
    if sen[i:i+4]=='NOUN':
        n=randint(0,3)
        if n==0:
            noun='tree'
        elif n==1:
            noun='horse'
        elif n==2:
            noun='bed'
        elif n==3:
            noun='sofa'
        print(noun)

        sen=sen[:i]+noun+sen[i+4:]
    i=i+1

print (sen)

wait=input('Enter a value ')
Code#2
from random import randint
sen="I am a NOUN, and I'll always be NOUNing around, and all the NOUNs are gonna hate it"
i=0
while i<len(sen):
    if sen[i:i+4]=='NOUN':
        n=randint(0,3)
        if n==0:
            noun='tree'
        elif n==1:
            noun='horse'
        elif n==2:
            noun='bed'
        elif n==3:
            noun='sofa'
        print(noun)

        sen=sen.replace(sen[i:i+4],noun)
    i=i+1

print (sen)

wait=input('Enter a value ')
In the second code, str.replace() replaces all instances of "NOUN" on the first iteration of the loop with the selected noun from the if statement. Conversely, the first code inserts the word at the index points, allowing for different nouns to be selected. Is that the performance difference you're inquiring about?
yes, that's exactly what I am asking about
but I still can't understand why it happened
The replace() method returns a copy of the string where all occurrences of a substring is replaced with another substring. When you rebuild the string from parts you are only replacing one occurrence. When using replace you do not need to search for "NOUN", the command does that work for you.
Thank youuuuu