简体   繁体   English

lstrip正在删除一个我不期望的字符

[英]lstrip is removing a character I wouldn't expect it to

The following code: 如下代码:

s = "www.wired.com"
print s
s = s.lstrip('www.')
print s

outputs: 输出:

www.wired.com
ired.com

Note the missing w on the second line. 注意第二行中缺少的w I'm not sure I understand the behavior. 我不确定我是否了解这种行为。 I would expect: 我期望:

www.wired.com
wired.com

EDIT: 编辑:

Following the first two answers, I now understand the behavior. 按照前两个答案,我现在了解了行为。 My question is now: how do I strip the leading www. 我现在的问题是: 如何剥离领先的www. without touching the rest ? 不碰其余部分

The argument to string.lstrip is a list of characters: string.lstrip的参数是一个字符列表:

>>> help(string.lstrip)
Help on function lstrip in module string:

lstrip(s, chars=None)
    lstrip(s [,chars]) -> string

    Return a copy of the string s with leading whitespace removed.
    If chars is given and not None, remove characters in chars instead.

>>>

It removes ALL occurrences of those leading characters. 它删除所有出现的那些前导字符。

print s.lstrip('w.')  # does the same!

[EDIT]: [编辑]:

If you wanted to strop the initial www. 如果您想过滤初始的www. , but only if it started with that, you could use a regular expression or something like: ,但前提是您必须使用正则表达式或类似以下内容:

s = s[4:] if s.startswith('www.') else s

According to the documentation: 根据文档:

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 相反,其值的所有组合都被剥离

You would achieve the same result by just saying: 只需说:

'www.wired.com'.lstrip('w.') 'www.wired.com'.lstrip(' 瓦特')

If you wanted something more general, I would do something like this: 如果您想要更一般的东西,我会做这样的事情:

i = find(s, 'www.')
if i >= 0:
   s = s[0:i] + s[i+4:]

To remove the leading www. 删除前导www.

>>> import re
>>> s = "www.wired.com"
>>> re.sub(r'^www\.', '', s)
'wired.com'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在熊猫中使用lstrip时删除多余的字符 - Removing extra character while using lstrip in pandas Lstrip 和 Rstrip 不起作用,需要帮助从 Python 中的 output 中删除文本 - Lstrip and Rstrip won't work, need help removing text from an output in Python 3 为什么我发布到PyPI的这个项目不能通过pip安装? - Why wouldn't this project I published to PyPI install with pip? lstrip方法无法产生我想要的 - lstrip method does not produce what I want 为什么 word.lstrip 不能分配给 function 调用? - Why can't word.lstrip be assigned to function call? 代码没有像我期望的那样交换案例 - Code isn't swapping cases as I expect it to 多线程不像我期望的那样工作 - Multithreading doesn't work like I expect it to 我的代码有什么问题? 当我打电话给新事件时,旧事件不会停止 - Whats wrong with my code? The old event wouldn't stop when I call the new one 为什么我不想在安装时将Python.exe添加到我的系统路径? - Why wouldn't I want to add Python.exe to my System Path at install time? SNOW ODBC 试图获取屏幕截图中的数据,但它就是不给它(我有权访问数据/权限) - SNOW ODBC trying to get to the data in the screenshot but it just wouldn't give it(I have access to the data/permissions)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM