lstrip/rstrip 和 removeprefix/removesuffix(Python 3.9)

最近在项目中遇到个问题,想把'user:user1'这个字符串的前缀user:删除掉,留取后面的user1,代码中使用了lstrip方法(用的是python2.7)。但是测试发现:

print 'user:user1'.lstrip('user:')

'1'

于是仔细查看了lstrip的文档说明:

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. The chars argument is not a prefix; rather, all combinations of its values are stripped:

也就是说,其参数 chars 虽然是一个字符串,但不是直接去除字串形式的 chars,而是在从左到右遍历原字符串,去除在 chars 中的字符,直到遇到第一个不在 chars 中的字符为止。

那么如何才能实现我们想要的功能呢?(将开头user:开头的字符串部分去掉)

查看python3.9发现,这个版本提供了removeprefix和removesuffix功能,于是我们实现了类似上面两个函数的功能(因为我们用的是python2.7,暂时没有升级到3.9以上版本的打算)。

>>>'user:user1'.removeprefix('user:')
'user1'
def remove_prefix(string, prefix):
    return string[len(prefix):] if string.startswith(prefix) else string

def remove_suffix(string, suffix):
    return string[:-len(suffix)] if string.endswith(suffix) else string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值