为什么 str.lstrip 去掉一个额外的字符? [英] Why does str.lstrip strip an extra character?

查看:27
本文介绍了为什么 str.lstrip 去掉一个额外的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>path = "/Volumes/Users";>>>path.lstrip('/音量')'s/用户'>>>path.lstrip('/卷')'用户'>>>

我希望 path.lstrip('/Volumes') 的输出是 '/Users'

解决方案

lstrip 是基于字符的,它从左端删除该字符串中的所有字符.

要验证这一点,请尝试以下操作:

"/Volumes/Users".lstrip("semuloV/") # 也返回 "Users";

由于 / 是字符串的一部分,因此将其删除.

您需要改用切片:

if s.startswith("/Volumes"):s = s[8:]

或者,在 Python 3.9+ 上,您可以使用 removeprefix:

s = s.removeprefix("/Volumes")

>>> path = "/Volumes/Users"
>>> path.lstrip('/Volume')
's/Users'
>>> path.lstrip('/Volumes')
'Users'
>>> 

I expected the output of path.lstrip('/Volumes') to be '/Users'

解决方案

lstrip is character-based, it removes all characters from the left end that are in that string.

To verify this, try this:

"/Volumes/Users".lstrip("semuloV/")  # also returns "Users"

Since / is part of the string, it is removed.

You need to use slicing instead:

if s.startswith("/Volumes"):
    s = s[8:]

Or, on Python 3.9+ you can use removeprefix:

s = s.removeprefix("/Volumes")

这篇关于为什么 str.lstrip 去掉一个额外的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆