Python Forum
str.replace affects the if statement!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
str.replace affects the if statement!
#1
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 ')
Reply
#2
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?
Reply
#3
yes, that's exactly what I am asking about
but I still can't understand why it happened
Reply
#4
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.
Reply
#5
Thank youuuuu
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search & Replace - Newlines Added After Replace dj99 3 3,354 Jul-22-2018, 01:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020