【问题标题】:python how to extract a number from a variable [duplicate]python如何从变量中提取数字[重复]
【发布时间】:2015-01-30 23:59:08
【问题描述】:

我想知道在 python 中是否可以从变量中提取某些整数并将其保存为单独的变量以供以后使用。

例如:

str1 = "numberone=1,numbertwo=2,numberthree=3"

newnum1 = [find first integer from str1]

newnum2 = [find second integer from str1]

answer = newnum1 * newnum2

print(answer)

【问题讨论】:

  • 你的输入是什么样的???
  • 是的,你当然可以解析字符串来提取你想要的。
  • 检查stackoverflow.com/questions/11339210/…,尝试一下,如果失败了,展示你尝试过的东西

标签: python variables integer


【解决方案1】:

你有一些选择:

使用str.split()

>>> [int(i.split('=')[1]) for i in str1.split(',')]
[1, 2, 3]

使用正则表达式:

>>> map(int,re.findall(r'\d',str1))
[1, 2, 3]

【讨论】:

    【解决方案2】:

    试试findall:

    num1, num2, num3 = re.findall(r'\d+', 'numberone=1,'
                                          'numbertwo=2,'
                                          'numberthree=3')
    

    现在num1 包含 字符串 1,num2 包含 2,num3 包含 3。

    如果您只需要两个数字(感谢@dawg),您可以简单地使用切片运算符:

    num1, num2=re.findall(r'\d+', the_str)[0:2]
    

    【讨论】:

    • 由于他只找两个数字,你可以考虑:num1, num2=re.findall(r'\d+', the_str)[0:2]
    【解决方案3】:
    (?<==)\d+(?=,|$)
    

    试试这个。查看演示。

    http://regex101.com/r/yR3mM3/19

    import re
    p = re.compile(ur'(?<==)\d+(?=,|$)', re.MULTILINE | re.IGNORECASE)
    test_str = u"numberone=1,numbertwo=2,numberthree=3"
    
    re.findall(p, test_str)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 2022-08-14
      相关资源
      最近更新 更多