一、案例1:最基础的字符串替换

text = "Hello World"
new_text = text.replace("World", "Python")
print(text)       # 输出: Hello World
print(new_text)   # 输出: Hello Python

二、案例2:控制替换次数

text = "apple apple apple"
new_text = text.replace("apple", "banana", 2)
print(new_text)  
# 输出:banana banana apple

三、案例3:多层替换

text = "the sky is blue, the sea is also blue"
new_text = text.replace("blue", "green").replace("sea", "ocean")
print(new_text)  
# 输出:the sky is green, the ocean is also green

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐