Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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:

777123456

Each 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:

1300

Instructions

  1. 1

    In a game, message is a message with the placeholder PLAYER in it, twice. Print the message with both PLAYERs replaced with the name in player: Ninja found a sword! Well done, Ninja! Keep the line player = "Ninja": the exercise also tries other names in it.

  2. 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 print New score: 1250500. Keep the line with score too.

Back

3/12

  1. 1. Upper and Lower Case
  2. 2. Trimming Spaces
  3. 3. Replacing Text
  4. 4. Quiz: Text Methods
  5. 5. Searching in Text
  6. 6. Beginnings and Ends
  7. 7. Splitting Text
  8. 8. Joining a List
  9. 9. Slices
  10. 10. Quiz: Slices
  11. 11. Decimal Places
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.