python - 如何在Python中返回url路径的子字符串?

标签 python string python-2.7 substring

我有这个网址

www.testing.com/drive/rayon.productlist.pagination.topage/2?t:ac=3686975/4441810

我想要2

我在 python 2.7 中尝试过:

s = 'www.testing.com/drive/rayon.productlist.pagination.topage/2?t:ac=3686975/4441810'
s = s.substring(s.indexOf("topage/") + 1);
s = s.substring(0, s.indexOf("?"));
print s

我收到了这个错误

AttributeError: 'str' object has no attribute 'substring'

最佳答案

您应该使用urlparse如果您需要 URL 的不同组成部分,请使用此函数。

>>> from urlparse import urlparse
>>> u = urlparse("www.testing.com/drive/rayon.productlist.pagination.topage/2?t:ac=3686975/4441810")
>>> u
ParseResult(scheme='', netloc='', path='www.testing.com/drive/rayon.productlist.pagination.topage/2', params='', query='t:ac=3686975/4441810', fragment='')
>>> u.path[-1]
'2'
>>> 

关于python - 如何在Python中返回url路径的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37069652/

相关文章:

python - 如何在Python中基于另一个数据框更改整个数据框值

确保函数的输入参数是 int/str 的 Pythonic 方法?

python - 在 namedtuple 中输入提示

python - 如何在Python中获取非数值数据的摘要

python - 模拟函数参数分配给 *args 和 **kwargs

string - 如何使用 erlang os :cmd()? 删除特殊字符/转义序列

string - 如何在现代 Delphi 中将 AnsiString 转换为整数?

python - 带有 if 语句的函数中的全局变量

c - 如何检查一个字符串是否以C中的另一个字符串开头?

python Pandas : Lookup table by searching for substring