Skip to content Skip to sidebar Skip to footer

How To Extract Numbers And Their Indices From A String In Python

I'm trying to write a function that will take a string and return a dictionary containing all of the numbers contained within the string and the index at which they begin. For exam

Solution 1:

In [44]: strs="1this is a 134 test15"

In [45]: {m.start(0):int(m.group(0)) for m in re.finditer("\d+", strs)}
Out[45]: {0: 1, 11: 134, 19: 15}

Solution 2:

>>>import re>>>text = "1this is a 134 test15">>>d = dict((m.start(), int(m.group())) for m in re.finditer(r'\d+', text))>>>d
{0: 1, 19: 15, 11: 134}

Solution 3:

The start() method of regular expression MatchObjects will provide the string offset of the current match.

Solution 4:

If you're looking for a function, i hope this may be useful. There's surely an easier way to do it. Howerver, this is what I've worked out. I tried my best :)

def function(string,dic={},p=0):

   iflen(string)==0:
      return dic

   else:
      i=0ifstring[0] in'1234567890':
        whilestring[i] in'0123456789':
          i+=1
          p+=1
        dic[p-len(string[:1])]=int(string[:i])
        string=string[i:]
        returnfunction(string,dic,p)else: 
        p+=1returnfunction(string[1:],dic,p)

Post a Comment for "How To Extract Numbers And Their Indices From A String In Python"