【问题标题】:How to extract 0207 from l=string instead of 207?如何从 l=string 中提取 0207 而不是 207?
【发布时间】:2019-11-10 08:55:50
【问题描述】:

让用户输入为0207a97,使用re 207从列表中提取而不是0207

str = input()
l = [int(i) for i in re.findall('\d+',str) if '9' not in i]

if len(l)>0:
    print(max(l))

【问题讨论】:

  • int 构造函数的常规行为:int("0297") --> 297

标签: python regex


【解决方案1】:

你可以使用

import re

s = "0207a97"
l = [(int(i), i) for i in re.findall('\d+',s) if '9' not in i]
if len(l)>0:
    print(max(l, key=lambda x: x[0])[1]) # => 0207

请参阅Python demo。即获取第一项为整数值,第二项为匹配字符串值的元组列表,然后仅比较第一项得到最大值,并打印找到的元组的第2项。

或者,您可能仍然只是获得re.findall(r'\d+', s) 结果列表,并使用key 参数和max。将其设置为int,列表中的值将作为整数进行比较:

l = [i for i in re.findall('\d+',s) if '9' not in i]
if len(l)>0:
    print(max(l, key=int))

another Python demo。来自docs

key 指定一个参数的函数,用于从 iterable 中的每个元素中提取比较键(例如,key=str.lower)。默认值为None(直接比较元素)。

【讨论】:

    【解决方案2】:

    在屏幕上打印后,您可以添加前导零。您可以阅读此内容以获得更好的说明:https://stackoverflow.com/a/13499182

    【讨论】:

      【解决方案3】:

      如果我们要在字符串中捕获非九个起始数字,也许这会简单地返回:

      import re
      
      print(re.match("^([0-8]+)", "0207a97").group(1))
      

      输出

      0207
      

      【讨论】:

        【解决方案4】:
        import re
        a='0207a97'
        a1=re.findall('(\d+)',a)
        a1[0] #output - 0207
        a1[1] #output - 97
        

        这将为您提供作为列表的输出。您可以根据需要修改列表。

        【讨论】:

          猜你喜欢
          • 2020-07-22
          • 1970-01-01
          • 1970-01-01
          • 2019-12-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-03
          • 1970-01-01
          相关资源
          最近更新 更多