pal*_*czy 2 python string python-2.7
使用Python 2.7,我遇到了以下问题:我有想要清理的网址,特别是我想摆脱"http://".
这有效:
>>> url = 'http://www.party.com'
>>> url.lstrip('http://')
'www.party.com'
Run Code Online (Sandbox Code Playgroud)
但为什么这不起作用?
>>> url = 'http://party.com'
>>> url.lstrip('http://')
'arty.com'
Run Code Online (Sandbox Code Playgroud)
它摆脱了'派对'的'p'.
谢谢您的帮助.
将参数lstrip视为字符,而不是字符串.
url.lstrip('http://')删除所有领先h,t,:,/从url.
str.replace改为使用:
>>> url = 'http://party.com'
>>> url.replace('http://', '', 1)
'party.com'
Run Code Online (Sandbox Code Playgroud)
如果你真正想要的是从网址获取主机名,你也可以使用urlparse.urlparse:
>>> urlparse.urlparse('http://party.com').netloc
'party.com'
>>> urlparse.urlparse('http://party.com/path/to/some-resource').netloc
'party.com'
Run Code Online (Sandbox Code Playgroud)