Python Forum
str.replace affects the if statement! - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: str.replace affects the if statement! (/thread-25417.html)



str.replace affects the if statement! - Eslam - Mar-29-2020

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 ')



RE: str.replace affects the if statement! - stullis - Mar-29-2020

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?


RE: str.replace affects the if statement! - Eslam - Mar-29-2020

yes, that's exactly what I am asking about
but I still can't understand why it happened


RE: str.replace affects the if statement! - deanhystad - Mar-30-2020

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.


RE: str.replace affects the if statement! - Eslam - Mar-30-2020

Thank youuuuu