简体   繁体   English

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

[英]How to use string.replace() in python 3.x

The string.replace() is deprecated on python 3.x. string.replace()在 python 3.x 上已弃用。 What is the new way of doing this?这样做的新方法是什么?

As in 2.x, usestr.replace() .在 2.x 中,使用str.replace()

Example:例子:

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

replace() is a method of <class 'str'> in python3: replace()是 python3 中<class 'str'>一个方法:

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

The replace() method in python 3 is used simply by: 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

You can use str.replace() as a chain of str.replace() .您可以使用str.replace()作为str.replace() 。 Think you have a string like 'Testing PRI/Sec (#434242332;PP:432:133423846,335)' and you want to replace all the '#',':',';','/' sign with '-' .你觉得你有一个像串'Testing PRI/Sec (#434242332;PP:432:133423846,335)' ,并要更换所有的'#',':',';','/'与招牌'-' You can replace it either this way(normal way),您可以通过这种方式(正常方式)替换它,

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

or this way(chain of str.replace() )或者这样( str.replace()链)

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

Try this:试试这个:

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

FYI, when appending some characters to an arbitrary, position-fixed word inside the string (eg changing an adjective to an adverb by adding the suffix -ly ), you can put the suffix at the end of the line for readability.仅供参考,当将一些字符附加到字符串内的任意位置固定词时(例如,通过添加后缀-ly将形容词更改为副词),您可以将后缀放在行尾以提高可读性。 To do this, use split() inside replace() :为此,请在replace()使用split() replace()

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

Official doc for str.replace of Python 3 Python 3 str.replace的官方文档

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

str.replace(old, new[, count]) str.replace(旧的,新的[,计数])

Return a copy of the string with all occurrences of substring old replaced by new.返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换。 If the optional argument count is given, only the first count occurrences are replaced.如果给出了可选参数计数,则仅替换第一个计数出现。

corresponding VSCode 's syntax notice is:对应的VSCode的语法说明是:

在此处输入图片说明

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

Two method to use str.replace使用str.replace两种方法

  • Method 1: use builtin str's replace -> str.replace(strVariable, old, new[, count])方法一:使用内置str的replace -> str.replace(strVariable, old, new[, count])
replacedStr1 = str.replace(originStr, "from", "to")
  • Method 2: use str variable's replace -> strVariable.replace(old, new[, count])方法二:使用str变量的replace -> strVariable.replace(old, new[, count])
replacedStr2 = originStr.replace("from", "to")

Full demo完整演示

code:代码:

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

output:输出:

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

screenshot:截屏:

在此处输入图片说明

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

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

Simple Replace: .replace(old, new, count) .简单替换: .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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM