# 示例代码:Python字符替换
# 使用 str.replace() 方法进行简单的字符替换
original_string = "hello world"
new_string = original_string.replace("world", "Python")
print(new_string) # 输出: hello Python
# 解释说明:
# str.replace(old, new) 方法会将字符串中的 old 子串替换为 new 子串。
# 在这个例子中,我们将 "world" 替换为 "Python"。
# 使用 re.sub() 方法进行更复杂的正则表达式替换
import re
text = "The rain in SPAIN stays mainly in the plain."
pattern = r"[A-Z]+" # 匹配所有大写字母组成的单词
replacement = "Country"
result = re.sub(pattern, replacement, text)
print(result) # 输出: The rain in Country stays mainly in the plain.
# 解释说明:
# re.sub(pattern, replacement, string) 方法使用正则表达式模式 pattern 查找并替换匹配的子串。
# 在这个例子中,我们将所有由大写字母组成单词(如 "SPAIN")替换为 "Country"。
上一篇:sort在python中的含义
下一篇:python贪吃蛇代码可复制
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站