当前位置: 移动技术网 > IT编程>脚本编程>Python > python字符串方法replace()简介

python字符串方法replace()简介

2019年05月06日  | 移动技术网IT编程  | 我要评论

特色婚庆,电气工程及其自动化大学排名,勤工助学征文

今天写replace方法的时候的代码如下:

1 message = "i really like dogs"
2 message.replace('dog','cat')
3 print(message)

本以为运行结果会是:i really like cats

 

出乎意料结果却是原字符串

 

查了一下才得知python中string是不可变的

>>> help(str.replace)
help on method_descriptor:
replace(...)
    s.replace(old, new[, count]) -> string
    
    return a copy of string s with all occurrences of substring
    old replaced by new.  if the optional argument count is
    given, only the first count occurrences are replaced.
>>> s='hello python,hello world,hello c++,hello java!'
>>> s.replace('hello','hello')#将字符串s中的所有'hello'子串,替换成'hello',返回替换后的字符串,原字符串s不变
'hello python,hello world,hello c++,hello java!'
>>> s
'hello python,hello world,hello c++,hello java!'
>>> s.replace('hello','hello',2)#将字符串s中的前2个'hello'子串,替换成'hello'
'hello python,hello world,hello c++,hello java!'
>>> s
'hello python,hello world,hello c++,hello java!'
>>> s.replace('wahaha','haha')#要替换的'wahaha'子串不存在,直接返回原字符串
'hello python,hello world,hello c++,hello java!'

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网