最近在项目中遇到个问题,想把'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