【问题标题】:How can I get int value from url如何从 url 获取 int 值
【发布时间】:2014-01-09 09:34:46
【问题描述】:

如果我有一个像examle/def/5/ 这样的url,我尝试通过使用从url 中找到int

re.findall([0-9],'examle/def/5/')

但我得到一个错误。

Traceback(最近一次调用最后一次):文件“”,第 1 行,in 文件“/usr/lib/python2.7/re.py”,第 177 行,在 findall 中返回 _compile(pattern, flags).findall(string) File "/usr/lib/python2.7/re.py", line 229, in _compile p = _cache.get(cachekey) TypeError: unhashable type: 'list'

我该怎么做?

【问题讨论】:

  • 什么错误?请分享回溯。
  • 回溯(最近一次调用最后):文件“”,第 1 行,在 文件“/usr/lib/python2.7/re.py”,第 177 行,在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'
  • 请使用回溯更新您的问题,而不是放在评论中。

标签: python regex python-2.7


【解决方案1】:

只是一种不使用正则表达式的不同方式。

 from string import digits
 url = 'examle/def/5/'
 nums = [i for i in list(url) if i in list(digits)]
 return "".join(nums)

【讨论】:

    【解决方案2】:

    使用“正则表达式”可能很容易

    虽然强大,但也很危险

    我不知道你的具体要求,

    如果您想从 uri 中的任何位置提取数字,是的,建议的解决方案有效

    >>> re.findall('[0-9]','examle/def/5/')
    ['5']
    

    但我假设您想从 uri 的“固定位置”获取数字。 如果是,你可能不想要这个结果

    >>> re.findall('[0-9]','examle5/def/5/')
    ['5', '5']
    

    我相信你可以修改正则表达式来完成这个,但是我会尽量避免正则表达式,因此我会这样做

    >>> 'examle5/def/5/'.split('/')[-2]
    '5'
    

    如果你想使用提取的值那么

    try:
        int('examle5/def/5/'.split('/')[-2])   =>> will produce 5 (without quotes)
    except ValueError:
        <<your code to handle when integer not present in url)
    

    【讨论】:

      【解决方案3】:

      确保导入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']
      

      【讨论】:

      • 好的,我明白了,实际上我没有在 [0-9] 中使用 ''...thanx
      • 我不是反对者,但我建议您使用 '\d+' 来捕获所有数字,而不仅仅是单个数字。
      • @lcfseth, \d+ 已经在答案代码中。现在添加了关于\d+ 的明确解释。感谢您的评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2013-05-18
      • 2016-08-20
      相关资源
      最近更新 更多