问题:如何在python 3.x中使用string.replace()
在python 3.x上不推荐使用string.replace()。这样做的新方法是什么?
回答 0
回答 1
replace()
是<class 'str'>
python3中的一种方法:
>>> 'hello, world'.replace(',', ':')
'hello: world'
回答 2
python 3中的replace()方法仅用于:
a = "This is the island of istanbul"
print (a.replace("is" , "was" , 3))
#3 is the maximum replacement that can be done in the string#
>>> Thwas was the wasland of istanbul
# Last substring 'is' in istanbul is not replaced by was because maximum of 3 has already been reached
回答 3
您可以使用str.replace()作为链str.replace() 。假设您有一个类似的字符串,'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
并且您想要将所有'#',':',';','/'
符号替换为'-'
。您可以通过这种方式(常规方式)进行替换,
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> str = str.replace('#', '-')
>>> str = str.replace(':', '-')
>>> str = str.replace(';', '-')
>>> str = str.replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
或这样(str.replace()的链)
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
回答 4
试试这个:
mystring = "This Is A String"
print(mystring.replace("String","Text"))
回答 5
仅供参考,将一些字符附加到字符串内任意位置固定的单词(例如,通过添加后缀-ly来将形容词更改为副词)时,可以将后缀放在行的末尾以提高可读性。为此,请split()
在内部使用replace()
:
s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'
回答 6
ss = s.replace(s.split()[1], +s.split()[1] + 'gy')
# should have no plus after the comma --i.e.,
ss = s.replace(s.split()[1], s.split()[1] + 'gy')
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。