我想知道是否可以從變量中提取某些整數並將其保存爲一個單獨的變量以供將來使用。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)
我想知道是否可以從變量中提取某些整數並將其保存爲一個單獨的變量以供將來使用。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)
(?<==)\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)
您有一些這方面的選擇:
使用str.split()
:
>>> [int(i.split('=')[1]) for i in str1.split(',')]
[1, 2, 3]
使用正則表達式:
>>> map(int,re.findall(r'\d',str1))
[1, 2, 3]
什麼是你輸入的樣子? ? – Hackaholic 2014-12-02 16:42:41
是的,你當然可以解析字符串來提取你想要的東西。 – jonrsharpe 2014-12-02 16:42:42
檢查http://stackoverflow.com/questions/11339210/how-to-get-integer-values-from-a-string-in-python,嘗試一下,如果你失敗,顯示你已經嘗試過 – fredtantini 2014-12-02 16:42:52