如何在python 3.x中使用string.replace()


280

在python 3.x上不推荐使用string.replace()。这样做的新方法是什么?


11
FWIW,我也有同样的困惑。Google“ python字符串替换”将我带到python 2.7中不推荐使用的旧字符串函数。恕我直言,该部分可以使用一个大胆的方框来解释“ string.xxx()”与“ xxx(string)”,并将人们引导至不建议使用的字符串方法,例如docs.python.org/library/stdtypes.html #string-methods
ToolmakerSteve

8
考虑到它被认为是理想的第一语言,Python文档绝对是个难题。这些东西经常出现在这里,但是由于其组织方式很差,因此通常不会被搜索引擎甚至他们自己的网站很好地索引。看一下ToolMakerSteve的链接,核心字符串函数集中在标准类型中。搜索字符串函数时不会出现这种情况。
Andrew S

10
需要明确的是:与string.replace()实际上不会被弃用关于Python 3
sboggs11


1
有时人们在意为[您的字符串变量] .replace时会写“ str.replace”。由于“ str”也是相关类的名称,因此可能会造成混淆。
TextGeek

Answers:


315

与2.x中一样,使用str.replace()

例:

>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'

4
“ re”(正则表达式)模块具有(某些?全部?)不推荐使用的字符串函数的替代项。在这种情况下,re.sub()
ToolmakerSteve

8
@ToolmakerSteve:string不推荐使用功能。str方法不是。
伊格纳西奥·巴斯克斯

6
FWIW,每当我使用google时,我似乎都会使用旧的不推荐使用的字符串函数。这是(不推荐使用的)字符串方法的链接。docs.python.org/3.3/library/stdtypes.html#string-methods 〜or_for_2〜 docs.python.org/2/library/stdtypes.html#string-methods
ToolmakerSteve

36
如果必须要溢出来浏览Python文档,那么显然存在问题。Python团队(如果您正在阅读)。梳理出来!
安德鲁·S

2
在对象而不是类上调用方法。'foo'.replace(...)
伊格纳西奥·巴斯克斯·阿布拉姆斯

108

replace()<class 'str'>python3中的一种方法:

>>> 'hello, world'.replace(',', ':')
'hello: world'

13

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

2
请记住,您也不能放3,它会改变所有的巧合。
Ender Look's

4

您可以使用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)'


1

仅供参考,将一些字符附加到字符串内任意位置固定的单词(例如,通过添加后缀-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'

0
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')

6
尽管此代码可以回答问题,但提供有关为什么和/或如何回答问题的其他上下文将大大提高其长期价值。请编辑您的答案以添加一些说明。
CodeMouse92 '16

正确的答案是前面说过的string.replace在python3中有效。
jorfus
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.