Dew*_*rld 249 python python-3.x
string.replace()在python 3.x上已弃用.这样做的新方法是什么?
Ign*_*ams 281
与2.x一样,使用str.replace().
例:
>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
Run Code Online (Sandbox Code Playgroud)
另请注意,点绑定比字符串连接更强,即使用括号:('Hello'+'world').replace('world','Guido')
kev*_*kev 103
replace()是<class 'str'>python3中的一种方法:
>>> 'hello, world'.replace(',', ':')
'hello: world'
Run Code Online (Sandbox Code Playgroud)
小智 11
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
Run Code Online (Sandbox Code Playgroud)
您可以使用str.replace()作为链str.replace() 。认为你有一个像这样的字符串'Testing PRI/Sec (#434242332;PP:432:133423846,335)',你想'#',':',';','/'用'-'. 您可以通过这种方式(正常方式)替换它,
>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> string = string.replace('#', '-')
>>> string = string.replace(':', '-')
>>> string = string.replace(';', '-')
>>> string = string.replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
Run Code Online (Sandbox Code Playgroud)
或者这样(str.replace()链)
>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
Run Code Online (Sandbox Code Playgroud)
str.replace的官方文档Python 3官方文档:Python 3str.replace
\n\nstr.replace(旧的,新的[,计数])
\n返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换。如果给出了可选参数 count,则仅替换第一个出现的 count。
\n
相应的VSCode语法提示是:
\n\nstr.replace(self: str, 旧的, 新的, 计数) -> str
\n
str.replacestr.replace(strVariable, old, new[, count])replacedStr1 = str.replace(originStr, "from", "to")\nRun Code Online (Sandbox Code Playgroud)\nstrVariable.replace(old, new[, count])replacedStr2 = originStr.replace("from", "to")\nRun Code Online (Sandbox Code Playgroud)\n代码:
\noriginStr = "Hello world"\n\n# Use case 1: use builtin str\'s replace -> str.replace(strVariable, old, new[, count])\nreplacedStr1 = str.replace(originStr, "world", "Crifan Li")\nprint("case 1: %s -> %s" % (originStr, replacedStr1))\n\n# Use case 2: use str variable\'s replace -> strVariable.replace(old, new[, count])\nreplacedStr2 = originStr.replace("world", "Crifan Li")\nprint("case 2: %s -> %s" % (originStr, replacedStr2))\nRun Code Online (Sandbox Code Playgroud)\n输出:
\ncase 1: Hello world -> Hello Crifan Li\ncase 2: Hello world -> Hello Crifan Li\nRun Code Online (Sandbox Code Playgroud)\n截屏:
\n\n\n小智 6
尝试这个:
mystring = "This Is A String"
print(mystring.replace("String","Text"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
402312 次 |
| 最近记录: |