python - 替换字符串后缀

标签 python

在 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/

相关文章:

python - boolean 数组元素的 AND 运算

python:如何在一副牌中生成成对的牌

python - 为什么要更改此变量?

python - Selenium 无法使用 python 抓取 Shopee 电子商务网站

python - 连接字符串列表中的选定字符串

python - 将键/值对的 Pyspark RDD 解析为 .csv 格式

python - 如何使函数从 Python 中的函数外部获取变量?

android - KIVY - Python 在按下按钮时继续执行

python - 如何在使用 DNNCLassifier 时可视化嵌入 - Tensorflow

python - 合并 csv 文件列和名称列