Python replace()

python 中的replace()函数有助于在用“new”子字符串替换“old”子字符串后返回原始字符串的副本。该函数还允许指定旧字符串需要替换的次数。

 **str.replace(old, new [, count]) ** #where old & new are strings 

replace()函数接受三个参数。如果没有给定 count 参数,replace()方法将用新的子字符串替换所有旧的子字符串。replace()方法也可以与数字和符号一起使用。

参数描述必需/可选
老的要替换的旧子字符串需要
新的将替换旧子串的新子串可选择的
数数希望用新的子字符串替换旧的子字符串的次数可选择的

返回值始终是替换后的新字符串。此方法执行区分大小写的搜索。如果找不到指定的旧字符串,它将返回原始字符串。

| 投入 | 返回值 |
| 线 | 字符串(旧的替换为新的) |

 string = 'Hii,Hii how are you'

# replacing 'Hii' with 'friends'
print(string.replace('Hii', 'friends'))

string = 'Hii, Hii how are you, Hii how are you, Hii'

# replacing only two occurences of 'Hii'
print(string.replace('Hii', "friends", 2)) 

输出:

 friends,friends how are you
Hii, friends how are you, friends how are you, Hii 
 string = 'Hii,Hii how are you'

# returns copy of the original string because of count zero
print(string.replace('Hii', 'friends',0))

string = 'Hii, Hii how are you, Hii how are you, Hii'

# returns copy of the original string because old string not found
print(string.replace('fine', "friends", 2)) 

输出:

 Hii,Hii how are you
Hii, Hii how are you, Hii how are you, Hii 

原创文章,作者:GL33U,如若转载,请注明出处:https://www.506064.com/n/127017.html

相关推荐