python中replace的用法
python 中的 replace() 函数用于在字符串中查找并替换指定的子字符串,其语法为:str.replace(old, new, count)。它可以替换所有匹配项(count=-1),或指定替换次数(count为正数),或不替换任何内容(count=0)。特殊情况下,如果子字符串不存在则不替换,如果 new 为空则删除子字符串,如果 count 为 0 则不替换。
Python 中 replace() 的用法
replace() 函数是 Python 中字符串方法,用于在字符串中查找并替换指定的子字符串。其语法格式如下:
str.replace(old, new, count)
其中:
使用方法:
my_string = "Hello, world!" result = my_string.replace("world", "Python") print(result) # 输出:Hello, Python!
my_string = "Hello, world! world!" result = my_string.replace("world", "Python", 1) print(result) # 输出:Hello, Python! world!
特殊情况:
示例:
my_string = " Hello, world! " result = my_string.replace(" ", "") print(result) # 输出:Hello,world!
number = 123 result = str(number).replace(",", ".") print(result) # 输出:123.0
html_string = "<p>Hello, <b>world</b>!</p>" result = html_string.replace("", ">") print(result) # 输出:<p>Hello, <b>world</b>!</p>
以上就是python中replace的用法的详细内容,更多请关注php中文网其它相关文章!