How to replace characters in a string using Python?

In Python, you can use the str.replace() method to replace characters in a string. This method takes two parameters – the first parameter is the character to be replaced, and the second parameter is the character to replace it with. For example:

s = "hello world"
new_s = s.replace("l", "x")
print(new_s)  # 输出: hexxo worxd

In addition, you can also use the re.sub() method for replacement, which is more flexible and can match characters to be replaced using regular expressions. For example:

import re

s = "hello world"
new_s = re.sub("l", "x", s)
print(new_s)  # 输出: hexxo worxd
Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds