Inconsistence string replace method - try it from your side

sd1 = ‘what we think, we become’
print(‘#######first replace statement######’)
sd1.replace(‘we’,‘you’) # first statement
print(‘######second replace statement######’)
sd1.replace(‘we’,‘you’,1) # second statement

Output of the program :
#######first replace statement######
######second replace statement######
‘what you think, we become’

first replace method output is not printed but second replace method is printed why it so? correct me if I am wrong

It’s always the best idea to use code blocks (</> button creates these), since your code has been corrupted by the Discourse software :frowning:

I’ve fixed your code, I think, and put it into a function:


def test_replace():
    sd1 = 'what we think, we become'
    print('#######first replace statement######')
    sd1.replace('we','you') # first statement
    print('######second replace statement######')
    sd1.replace('we','you',1) # second statement

test_replace()

If I run it, I get:

$ python3 replace.py
#######first replace statement######
######second replace statement######

This shows the key thing here: the string is never printed. I suspect that your interpreter is responsible for printing out the (unaltered) sd1. But the invocations of XX.replace are not getting sent to stdout.

1 Like

Thanks Rob, down the line I will keep the code in code block. I am using Jupyter Notes to run the program, need to check this pro on other IDEs (VS code).

Thanks,
Uttam Chavan