项目里需要对字符进行处理,将字符串结尾的’_all’去掉,果断写出代码
>>> string.rstrip('_all')
一切貌似正常
但不正常的现象出现了
>>> 'xxxxxl_all'.rstrip('_all')
输出结果竟然是:
xxxxx
而不是我们期望的
xxxxxl
所以,这是怎么回事呢?
查了一下官方文档:
https://docs.python.org/3/library/stdtypes.html#str.rstrip
但也没发现有什么规律
在群里问了一下,大神的解释是:
发现文档中说去除字符首尾特定字符的方法为:removeprefix和.removesuffix
但这两个方法都是3.9版才开始有的。
如果不想换环境,也可以自己写个方法:
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
def remove_suffix(text, suffix):
if text.endswith(suffix):
return text[:-len(suffix)]
return text