How to use the replace function in Python to specify the replacement character?

In Python, the replace() method can be used to specify the characters to replace. This method takes two parameters, the first one being the character or string to be replaced, and the second one being the character or string to replace it with.

Here is an example of replacing characters using the replace() method:

string = "Hello, World!"
new_string = string.replace("o", "a")
print(new_string)

The output result is:

HellA, Warld!

In the above example, we replaced all lowercase letters “o” in the string ‘string’ with lowercase letter “a” and saved the result in the variable new_string. Finally, we printed out the modified string.

You can call the replace() method multiple times if you want to replace multiple characters or strings. For example:

string = "Hello, World!"
new_string = string.replace("o", "a").replace("l", "z")
print(new_string)

The output is:

Hezza, Warzd!

In the example above, we first replaced all lowercase “o” in the string with lowercase “a”, then replaced all lowercase “l” in the modified string with lowercase “z”. Finally, we printed the final replacement result.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds