在 Python 中,我们有 .replace()
替换字符串中的子字符串,现在,从 Python 3.9 开始,我们有 .removesuffix()
从字符串中删除特定后缀。
我们如何以尽可能简单的方式(最好是一小行)替换Python中的后缀?
>>> string1 = "hello.world.wo"
>>> string2 = "hello.world"
>>>
>>> string1.removesuffix(".wo")
'hello.world'
>>>
>>> string2.removesuffix(".wo")
'hello.world'
>>>
>>> string1.replace(".wo", ".he")
'hello.herld.he'
>>>
>>> string2.replace(".wo", ".he")
'hello.herld'
>>>
>>> [ SOLUTION HERE with string1 ]
'hello.world.he'
>>>
>>> [ SAME SOLUTION HERE with string2 ]
'hello.world'
最佳答案
您可以使用正则表达式 sub
,这是一个更强大的字符串操作工具:
import re
string1 = "hello.world.wo"
string2 = "hello.world"
pattern = "\.wo$" # escape dot, $ means end of string
string1 = re.sub(pattern, ".he", string1)
print(string1)
string2 = re.sub(pattern, ".he", string2)
print(string2)
如果没有正则表达式,您也可以只检查字符串是否以后缀结尾,如果是,则手动剪切它:
string1 = "hello.world.wo"
suffix = ".wo"
if string1.endswith(suffix):
string1 = string1[:-len(suffix)] + ".he"
print(string1)
可以使用 if 表达式来缩短 if block :
suffix = ".wo"
string1 = string1[:-len(suffix)] + ".he" if string1.endswith(suffix) else string1
关于python - 替换字符串后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76826611/