今天寫replace方法的時候的代碼如下: 本以為運行結果會是:I really like cats 出乎意料結果卻是原字元串 查了一下才得知python中string是不可變的 >>> help(str.replace)Help on method_descriptor:replace(...) ...
今天寫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!'