Python removesuffix() 语法
removesuffix() 是 Python 字符串的一个方法,它会删除字符串的后缀(即末尾的指定子串),并返回字符串的剩余部分。
语法:
str.removesuffix(suffix)说明:
removesuffix() 方法接收单个参数。
suffix(必选):字符串末尾的子串。如果字符串不以该后缀结尾,则直接返回原字符串的副本。如果 suffix 参数是空字符串,也会返回原字符串的副本。
注意: removesuffix() 不会修改原字符串,而是返回一个新字符串。
Python removesuffix() 摘要
| 使用频率 | 中 |
|---|---|
| 修改原字符串 | 否 |
| 官方文档 | 查看 |
| 相关方法 | removeprefix()、endswith()、rstrip() |
Python removesuffix() 示例
接下来,我们通过一个简单的例子来讲解 Python removesuffix() 方法是如何使用的。
示例 1:removesuffix() 基本用法
s = 'logo.jpg'
result = s.removesuffix('.jpg')
print(s)
print(result)运行结果如下。
logo.jpg
logo分析:
从结果可以看到,removesuffix() 并不会修改原字符串。
示例 2:后缀不存在的情况
s = 'logo.jpg'
result = s.removesuffix('.png')
print(result)运行结果如下。
logo.jpg分析:
当后缀不存在时,removesuffix() 会返回原字符串的副本。
removeprefix() 和 removesuffix()
removeprefix() 和 removesuffix() 是一对 “好基友” 关系,它们的区别如下。
removeprefix():删除的是字符串的前缀,并返回一个新字符串。removesuffix():删除的是字符串的后缀,并返回一个新字符串。
常见问题
1. 如何在 Python 3.9 以下版本使用 removesuffix() 方法呢?
我们可以手动实现 removesuffix() 的逻辑,比如:
def removesuffix(s, suffix):
return s[:-len(suffix)] if suffix and s.endswith(suffix) else s2. 如果 removesuffix() 的参数是一个非字符串,此时会有什么问题呢?
removesuffix() 参数必须是字符串类型,否则会抛出 TypeError 异常。
'text'.removesuffix(123) # (报错)TypeError