python - Extraction of 2 or more digit number into a list from string like 12+13 -
i'm trying extract numbers string "12+13"
.
when extract numbers list becomes [1,2,1,3]
actually want list take numbers [12,13]
, 12,13 should integers also.
i have tried level best solve this,the following code
but still has disadvantage .
i forced put space @ end of string...for it's correct functioning.
my code
def extract(string1): l=len(string1) pos=0 num=[] continuity=0 in range(l): if string[i].isdigit()==true: continuity+=1 else: num=num+ [int(string[pos:continuity])] continuity+=1 pos=continuity return num string="1+134-15 "#added spaces @ end of string num1=[] num1=extract(string) print num1
the other answer great (as of now), want provide detailed explanation. what trying split string on "+" symbol. in python, can done str.split("+")
.
when translates code, turns out this.
ourstr = "12+13" ourstr = ourstr.split("+")
but, don't want convert integers? in python, can use list comprehension int()
achieve result.
to convert entire array ints, can use. pretty loops on each index, , converts string integer.
str = [int(s) s in ourstr]
combining together, get
ourstr = "12+13" ourstr = ourstr.split("+") ourstr = [int(s) s in ourstr]
but lets might other unknown symbols in array. @idos used, idea check make sure number before putting in array.
we can further refine code to:
ourstr = "12+13" ourstr = ourstr.split("+") ourstr = [int(s) s in ourstr if s.isdigit()]
Comments
Post a Comment