Python Biult-in Methods

50 views Asked by At

I am really confused about the replace python method. i used the replace function in two instances but the output is really confusing. This is the code below

story = 'there was once an old woman'

story2 = story.replace('an', 'a') .replace('old', 'young'))
print(story2)

and when i run the code below. the output becomes. there was once a young woma someone please tell me why was deleted from the woman.

2

There are 2 answers

2
Stuart On

Your code does not match the image. The code is correct, but the code from the image is incorrect.

The second n was removed from woman because .replace() replaces all occurrences. To only replace n instances, pass a number.

story = 'there was once an old woman'
story2 = story.replace('an', 'a', 1).replace('old', 'young')
print(story2)
# 'there was once a young woman'

You can chain the .replace() functions just fine.

1
hifromdev On

Screenshot reference:

The reason why woman turns into woma is because the 2 last letters of woman is 'an'. the .replace() function is set to replace all of the 'an's to 'a's. Since woman has 'an' as its last 2 letters, the 'an' is replaced with 'a' creating the illusion that the 'n' disappeared when actually 'an' was replaced with 'a'.

The second .replace("old", "young") function is placed on the 'a' string and since the word 'old' does not exist in this string. Nothing is changed in the output.

Basically, that screenshot has a lot of syntaxes that is highly likely to be unintended and wrong.