当前位置:   article > 正文

[Python] replace函数_replace函数python

replace函数python

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

语法

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

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

参数 

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

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

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

返回值

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

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

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

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

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

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

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

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

  1. original_str = 'My Name is Andy.'
  2. # My Name IS Andy.
  3. print(original_str.replace('is','IS'))
  4. # My Name is Andy.
  5. print(original_str)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/212182
推荐阅读
相关标签
  

闽ICP备14008679号