Python字符串的replace()方法:实用的字符串处理工具
replace()是 Python 字符串所具备的一个方法,它的作用是对字符串的子串进行替换。其语法格式为:

调用 string 的 replace 方法,将 old 替换为 new,可指定替换的次数 count
- old - 将被替换的子串
- new - 新的子串,用于替换old子串
- count - 可选,替换不超过 count 次例如:
python
>>> 'hello'.replace('l', 'x')
'hexxo'
'hello' 这个字符串,将其中的 'l' 替换为 'x',并且只替换前 2 个 'l' 。
'hexxollo'
这里的 replace()方法会将字符串'hello'里的 l 替换为 x 。因为没有指定 count 参数,所以会把所有的 l 都进行替换。
如果指定的 count 为 2,那么就仅仅替换两个 l。这种方法在字符串的清理以及文本的处理方面有着很大的用处。例如:一是去除空白字符。
python
"hello" 去掉空格后的结果
'hello'
- 替换HTML实体:
python
将“Bread & Butter”中的“&”替换为“*”
' Bread * Butter '
- 替换制表符/\t、换行符/\n:
python
'hello world'
等等。所以,replace()是一个很实用的字符串处理方式,能够用于清理和规范字符串,对特定的子串进行替换,在 Python 的字符串操作以及文本处理方面应用很广泛。