How can you replace specific content in text using Python?

In Python, the str.replace() method can be used to replace specified content in text. The str.replace() method takes two parameters, the first parameter being the content to be replaced and the second parameter being the content to replace it with. Here is an example:

text = "Hello, world!"
new_text = text.replace("world", "Python")
print(new_text)

Output:

Hello, Python!

In this example, we replace the string “world” with “Python”. The str.replace() method returns a new string with the replacement, without changing the original string.

If you want to replace all matches in the text, you can use regular expressions and the re.sub() method. Here is an example:

import re

text = "Hello, 12345! 67890!"
new_text = re.sub(r"\d+", "NUM", text)
print(new_text)

Output:

Hello, NUM! NUM!

In this example, we use the regular expression \d+ to match all numbers and replace them with the string “NUM”. The re.sub() method returns the new string with replacements, without changing the original string.

I hope this helps! Feel free to ask if you have any other questions.

bannerAds