Replacing Text
The method replace() returns a new text in which one part is replaced with another. In the parentheses, write what to look for and then what to put in its place:
message = "I love cats. My cats love me."
print(message.replace("cats", "dogs"))This prints:
I love dogs. My dogs love me.replace() replaces the part everywhere it finds it, not just the first time. It compares exactly, so case matters: "Cats are great".replace("cats", "dogs") finds no cats with a small c and returns the text as it was, Cats are great. When it finds nothing, there's no error.
To remove a part of a text, replace it with an empty text, "": two quotes with nothing between them.
phone = "777 123 456"
digits = phone.replace(" ", "")
print(digits)This prints:
777123456Each replace() returns a text, so you can chain them. That's useful before you turn a text into a number, because int() only understands a whole number written in digits. int("$1,299") ends with ValueError: invalid literal for int() with base 10: '$1,299', but without the dollar sign and the comma, it works:
price = "$1,299"
number = price.replace("$", "").replace(",", "")
print(int(number) + 1)This prints:
1300Instructions
- 1
In a game,
messageis a message with the placeholderPLAYERin it, twice. Print the message with bothPLAYERs replaced with the name inplayer:Ninja found a sword! Well done, Ninja!Keep the lineplayer = "Ninja": the exercise also tries other names in it. - 2
The score comes as text, with commas between groups of digits. Remove the commas, turn the score into a whole number with
int(), add 500 for the sword and printNew score: 1250500. Keep the line withscoretoo.