Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python如何从变量中提取数字_Python_Variables_Integer - Fatal编程技术网

python如何从变量中提取数字

python如何从变量中提取数字,python,variables,integer,Python,Variables,Integer,我想知道在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) (?试试: 现在num1包含字符串1,num2包含

我想知道在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)
(?试试:

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

如果您只需要两个数字(多亏了@dawg),只需使用slice操作符即可:

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

您对此有一些选择:

使用str.split()

使用正则表达式:

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

你的输入是什么样子的???是的,你当然可以解析字符串来提取你想要的。检查,尝试一些东西,如果失败,展示你的尝试。因为他只寻找两个数字,你可以考虑:
num1,num2=re.findall(r'\d+',the_str)[0:2]
num1, num2, num3 = re.findall(r'\d+', 'numberone=1,'
                                      'numbertwo=2,'
                                      'numberthree=3')
num1, num2=re.findall(r'\d+', the_str)[0:2]
>>> [int(i.split('=')[1]) for i in str1.split(',')]
[1, 2, 3]
>>> map(int,re.findall(r'\d',str1))
[1, 2, 3]