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


Messages In This Thread
str.replace affects the if statement! - by Eslam - Mar-29-2020, 10:01 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Search & Replace - Newlines Added After Replace dj99 3 4,408 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