[Python] replace函数

replace函数用于把字符串中的子字符串替换成指定字符串

语法

str.replace(oldvalue, newvalue[, count])

提示Tips: 如果参数只指定了oldvalue以及newvalue,未指定count,则将替换所有出现的指定子字符串oldvalue 

参数 

oldvalue:将被替换的子字符串(必需)

newvalue:用于替换oldvalue的子字符串(必需)

count:数值次数,指定要替换多少个oldvalue(可选)

返回值

返回字符串中的oldvalue替换成newvalue后生成的新字符串,如果指定了第三个参数count,则替换不超过count次

例1: 把字符串words中的每个空格替换成"%20"

words = "We are from China."
res = words.replace(' ', '%20')
# We%20are%20from%20China.
print(res)

例2: 将txt字符串中所有的"is"替换成"was"

txt = "this is a test, this is a test."
res = txt.replace("is", "was")
# thwas was a test, thwas was a test.
print(res)

例3: 将txt字符串中前两次出现的"is"替换成"was" 

txt = "this is a test, this is a test."
res = txt.replace("is", "was", 2)
# thwas was a test, this is a test.
print(res)

注意:replace函数不会改变原来字符串的内容

original_str = 'My Name is Andy.'
# My Name IS Andy.
print(original_str.replace('is','IS'))
# My Name is Andy.
print(original_str)

你可能感兴趣的:(Python,python)