How to use the replace function in Python to replace multiple content?

In Python, the replace() function can be used to replace content within a string. If multiple replacements are needed, consecutive replace() function calls can be used.

Here is an example code demonstrating how to use the replace() function to replace multiple items.

text = "Hello world, hello Python!"

# 替换多个内容
new_text = text.replace("Hello", "Hi").replace("world", "everyone").replace("Python", "programming")

print(new_text)

The output result is:

Hi everyone, hi programming!

In the example above, we first call the replace() function to replace the first content to be replaced with the new content, and then call the replace() function again to replace the second content to be replaced with the new content, and so on. Finally, we get the replaced string new_text.

It is important to note that the replace() function does not modify the original string, but instead returns a new string with the replacements. Therefore, it is necessary to assign the replacement result to a new variable (such as new_text) or directly use the replaced result.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds