2013-10-17 71 views
2

隨着Python 2.7,我遇到了以下問題:我有我想要清理的urls,特別是我想擺脫「http://」。lstrip去除字母

這工作:

>>> url = 'http://www.party.com' 
>>> url.lstrip('http://') 
'www.party.com' 

但爲什麼這個不行?

>>> url = 'http://party.com' 
>>> url.lstrip('http://') 
'arty.com' 

它從'派對'中擺脫'p'。

謝謝你的幫助。

回答

9

lstrip的參數看作是字符,而不是字符串。

url.lstrip('http://')刪除所有領先ht:,從url/

使用str.replace代替:

>>> url = 'http://party.com' 
>>> url.replace('http://', '', 1) 
'party.com' 

如果你真正想要的是從URL獲得主機名,你也可以使用urlparse.urlparse

>>> urlparse.urlparse('http://party.com').netloc 
'party.com' 
>>> urlparse.urlparse('http://party.com/path/to/some-resource').netloc 
'party.com'