2014-12-02 48 views
-2

我想知道是否可以從變量中提取某些整數並將其保存爲一個單獨的變量以供將來使用。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) 
+0

什麼是你輸入的樣子? ? – Hackaholic 2014-12-02 16:42:41

+0

是的,你當然可以解析字符串來提取你想要的東西。 – jonrsharpe 2014-12-02 16:42:42

+0

檢查http://stackoverflow.com/questions/11339210/how-to-get-integer-values-from-a-string-in-python,嘗試一下,如果你失敗,顯示你已經嘗試過 – fredtantini 2014-12-02 16:42:52

回答

1

嘗試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] 
+1

因爲他是隻會尋找兩個數字,你可能會考慮:'num1,num2 = re.findall(r'\ d +',the_str)[0:2]' – dawg 2014-12-02 16:48:05

0
(?<==)\d+(?=,|$) 

嘗試this.See演示。

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) 
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]