string.replace(old, new[, count])
# 将字符串中的Alice替换为Bob
str1 = "Hello, Alice. How are you, Alice?"
new_str1 = str1.replace("Alice", "Bob")
print(new_str1) # Hello, Bob. How are you, Bob?
# 只替换一次,将Alice替换为Bob
str2 = "Hello, Alice. How are you, Alice?"
new_str2 = str2.replace("Alice", "Bob", 1)
print(new_str2) # Hello, Bob. How are you, Alice?
string.translate(table)
# 将字符串中的数字替换为@
str3 = "12345"
translation = str.maketrans("0123456789", "@@@@@@@@@@")
new_str3 = str3.translate(translation)
print(new_str3) # @@@@@
# 将字符串中的元音字母替换为*
str4 = "Hello, world!"
translation = str.maketrans("aeiouAEIOU", "*")
new_str4 = str4.translate(translation)
print(new_str4) # H*ll*, w*rld!
re.sub(pattern, repl, string, count=0)
import re
# 将字符串中的Alice替换为Bob
str1 = "Hello, Alice. How are you, Alice?"
new_str1 = re.sub("Alice", "Bob", str1)
print(new_str1) # Hello, Bob. How are you, Bob?
# 只替换一次,将Alice替换为Bob
str2 = "Hello, Alice. How are you, Alice?"
new_str2 = re.sub("Alice", "Bob", str2, 1)
print(new_str2) # Hello, Bob. How are you, Alice?
标签: 智能AI