ChatGPT解决这个技术问题 Extra ChatGPT

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

string.replace() 在 python 3.x 上已弃用。这样做的新方法是什么?

FWIW,我也有同样的困惑。谷歌“python 字符串替换”将我带到了 python 2.7 中不推荐使用的旧字符串函数。恕我直言,该部分可以使用一个大的粗体框来解释“string.xxx()”与“xxx(string)”,并将人们引导到非弃用的字符串方法,例如 docs.python.org/library/stdtypes.html#string-methods
考虑到它被吹捧为理想的第一语言,Python 文档绝对是一团糟。很多时候,这些东西就在那里,但由于其组织方式不佳,搜索引擎甚至他们自己的网站通常都无法很好地对其进行索引。查看 ToolMakerSteve 的链接,核心字符串函数被归为标准类型。当您搜索字符串函数时,这不会出现。
需要明确的是: string.replace() 实际上并没有在 Python 3 上被弃用。
有时人们写“str.replace”的意思是[你的字符串变量].replace。因为 'str' 也是相关类的名称,这可能会造成混淆。

B
Boris Verkhovskiy

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

例子:

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

“re”(正则表达式)模块有替代(一些?全部?)不推荐使用的字符串函数。在这种情况下,re.sub()
@ToolmakerSteve:string 函数已弃用。 str 方法不是。
FWIW,每当我用谷歌搜索时,我似乎最终都会使用旧的不推荐使用的字符串函数。这是(未弃用的)字符串方法的链接。 docs.python.org/3.3/library/stdtypes.html#string-methods ~or_for_2~ docs.python.org/2/library/stdtypes.html#string-methods
如果我必须通过堆栈溢出来浏览 Python 文档,那么显然存在问题。如果你正在阅读 Python 团队。梳理出来!
调用对象的方法,而不是类。 'foo'.replace(...)
k
kev

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

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

佚名

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,它会改变所有的巧合。
K
Kushan Gunasekera

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

或这种方式(str.replace() 链)

>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'

Z
Zoe stands with Ukraine

尝试这个:

mystring = "This Is A String"
print(mystring.replace("String","Text"))

c
crifan

Python 3 的 str.replace 的官方文档

官方文档:Python 3's str.replace

str.replace(old, new[, count]) 返回字符串的副本,其中所有出现的子字符串 old 都替换为 new。如果给定了可选参数 count,则仅替换第一个 count 出现。

对应的 VSCode 的语法说明是:

https://i.stack.imgur.com/aDYN3.png

str.replace(self: str, old, new, count) -> str

使用 str.replace 的两种方法

方法1:使用内置str的replace -> str.replace(strVariable, old, new[, count])

replacedStr1 = str.replace(originStr, "from", "to")

方法2:使用str变量的replace -> strVariable.replace(old, new[, count])

replacedStr2 = originStr.replace("from", "to")

完整演示

代码:

originStr = "Hello world"

# Use case 1: use builtin str's replace -> str.replace(strVariable, old, new[, count])
replacedStr1 = str.replace(originStr, "world", "Crifan Li")
print("case 1: %s -> %s" % (originStr, replacedStr1))

# Use case 2: use str variable's replace -> strVariable.replace(old, new[, count])
replacedStr2 = originStr.replace("world", "Crifan Li")
print("case 2: %s -> %s" % (originStr, replacedStr2))

输出:

case 1: Hello world -> Hello Crifan Li
case 2: Hello world -> Hello Crifan Li

截屏:

https://i.stack.imgur.com/A0f1Q.png

我的相关(中文)帖子:【详解】Python 3中字符串的替换str.replace


O
Ooker

仅供参考,当将一些字符附加到字符串中任意位置固定的单词(例如,通过添加后缀 -ly 将形容词更改为副词),您可以将行尾的后缀是为了便于阅读。为此,请在 replace() 中使用 split()

s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'

D
Dr. Robert Brownell

简单替换: .replace(old, new, count) 。

text = "Apples taste Good."
print(text.replace('Apples', 'Bananas'))          # use .replace() on a variable
Bananas taste Good.          <---- Output

print("Have a Bad Day!".replace("Bad","Good"))    # Use .replace() on a string
Have a Good Day!             <----- Output

print("Mom is happy!".replace("Mom","Dad").replace("happy","angry"))  #Use many times
Dad is angry!                <----- Output

Z
Zoe stands with Ukraine
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')

虽然此代码可能会回答问题,但提供有关它为什么和/或如何回答问题的额外上下文将显着提高其长期价值。请edit您的回答以添加一些解释。
正确答案是前面所说的 string.replace 在 python3 中有效。