簡體   English   中英

lstrip正在刪除一個我不期望的字符

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

如下代碼:

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

輸出:

www.wired.com
ired.com

注意第二行中缺少的w 我不確定我是否了解這種行為。 我期望:

www.wired.com
wired.com

編輯:

按照前兩個答案,我現在了解了行為。 我現在的問題是: 如何剝離領先的www. 不碰其余部分

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.

>>>

它刪除所有出現的那些前導字符。

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

[編輯]:

如果您想過濾初始的www. ,但前提是您必須使用正則表達式或類似以下內容:

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

根據文檔:

該字符參數是一個字符串指定字符被刪除...的字符參數不是前綴 ; 相反,其值的所有組合都被剝離

只需說:

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

如果您想要更一般的東西,我會做這樣的事情:

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

刪除前導www.

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM