# 示例代码:使用 replace 方法替换字符串中的子字符串
# 基本用法:替换所有出现的子字符串
original_string = "hello world"
new_string = original_string.replace("world", "Python")
print(new_string) # 输出: hello Python
# 替换指定次数的子字符串
text = "one plus one equals two"
replaced_text = text.replace("one", "1", 1)
print(replaced_text) # 输出: 1 plus one equals two
# 使用 replace 处理多空格情况
sentence = " this is a test "
cleaned_sentence = sentence.replace(" ", " ").replace(" ", " ").strip()
print(cleaned_sentence) # 输出: this is a test
# 注意:replace 方法是区分大小写的
case_sensitive = "Hello Hello hello"
result = case_sensitive.replace("Hello", "Hi")
print(result) # 输出: Hi Hi hello
replace(old, new):将字符串中的所有 old 子字符串替换为 new。replace(old, new, count):只替换前 count 次出现的 old 子字符串。replace() 是区分大小写的,因此 "Hello" 和 "hello" 会被视为不同的子字符串。上一篇:python的文件扩展名
下一篇:升级python版本命令
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站