lstrip 去掉字母 [英] lstrip gets rid of letter
问题描述
使用 Python 2.7 时,我遇到了以下问题:我想清理网址,特别是我想去掉http://".
这有效:
<预><代码>>>>url = 'http://www.party.com'>>>url.lstrip('http://')'www.party.com'但是为什么这不起作用?
<预><代码>>>>url = 'http://party.com'>>>url.lstrip('http://')'arty.com'它去掉了 'party' 中的 'p'.
感谢您的帮助.
将 lstrip
的参数视为字符,而不是字符串.
url.lstrip('http://')
从 url<中删除所有前导
h
, t
, :
, /
/代码>.
使用 str.replace
代替:
如果你真正想要的是从 url 获取主机名,你也可以使用 urlparse.urlparse
:
With Python 2.7, I ran into the following problem: I have urls that I would like to clean, in particular I'd like to get rid of "http://".
This works:
>>> url = 'http://www.party.com'
>>> url.lstrip('http://')
'www.party.com'
But why does this not work?
>>> url = 'http://party.com'
>>> url.lstrip('http://')
'arty.com'
It gets rid of 'p' from 'party'.
Thank you for your help.
Think the argument of lstrip
as characters, not a string.
url.lstrip('http://')
removes all leading h
, t
, :
, /
from url
.
Use str.replace
instead:
>>> url = 'http://party.com'
>>> url.replace('http://', '', 1)
'party.com'
If what you really want is get hostname from the url, you can also use urlparse.urlparse
:
>>> urlparse.urlparse('http://party.com').netloc
'party.com'
>>> urlparse.urlparse('http://party.com/path/to/some-resource').netloc
'party.com'
这篇关于lstrip 去掉字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!