Python 中的 replace() 函数用于在字符串中查找并替换指定的子字符串,其语法为:str.replace(old, new, count)。它可以替换所有匹配项(count=-1),或指定替换次数(count为正数),或不替换任何内容(count=0)。特殊情况下,如果子字符串不存在则不替换,如果 new 为空则删除子字符串,如果 count 为 0 则不替换。

Python 中 replace() 的用法
replace() 函数是 Python 中字符串方法,用于在字符串中查找并替换指定的子字符串。其语法格式如下:
<code class="python">str.replace(old, new, count)</code>
其中:
使用方法:
立即学习“Python免费学习笔记(深入)”;
<code class="python">my_string = "Hello, world!"
result = my_string.replace("world", "Python")
print(result) # 输出:Hello, Python!</code><code class="python">my_string = "Hello, world! world!"
result = my_string.replace("world", "Python", 1)
print(result) # 输出:Hello, Python! world!</code>特殊情况:
示例:
<code class="python">my_string = " Hello, world! "
result = my_string.replace(" ", "")
print(result) # 输出:Hello,world!</code><code class="python">number = 123
result = str(number).replace(",", ".")
print(result) # 输出:123.0</code><code class="python">html_string = "<p>Hello, <b>world</b>!</p>"
result = html_string.replace("<", "<").replace(">", ">")
print(result) # 输出:<p>Hello, <b>world</b>!</p></code>以上就是python中replace的用法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号