lstrip 去掉字母 [英] lstrip gets rid of letter

查看:30
本文介绍了lstrip 去掉字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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 = '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'

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆