如果我有一个 url
喜欢examle/def/5/
,我试图找到 int
来自 url
的值通过使用
re.findall([0-9],'examle/def/5/')
但是我得到一个错误。
Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/re.py", line 177, in findall return _compile(pattern, flags).findall(string) File "/usr/lib/python2.7/re.py", line 229, in _compile p = _cache.get(cachekey) TypeError: unhashable type: 'list'
我该怎么做?
最佳答案
确保导入re
。
>>> import re
将第一个参数作为字符串对象传递。 (没有引号 [0-9]
列表文字等同于 [-9]
。)
>>> re.findall('[0-9]','examle/def/5/')
['5']
顺便说一句,你可以使用 \d
而不是 [0-9]
来匹配数字(使用 r'raw string'
你不不需要转义 \
):
>>> re.findall(r'\d','examle/def/5/')
['5']
>>> re.findall(r'\d','examle/def/567/')
['5', '6', '7']
如果要返回单个数字而不是多个数字,请使用 \d+
:
>>> re.findall(r'\d+','examle/def/567/')
['567']
关于python - 如何从 url 获取 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20705035/