sandeep
sandeep

Reputation: 3345

How to extract a number from a string in python

I have a string coming from db, for example:

"any string coming from db[090876]"

I want to just fetch the numeric data and use it. In this case I just want 090876. How can I do it in Python/Django? I have tried with 're' but no luck.

Upvotes: 1

Views: 247

Answers (2)

suhailvs1
suhailvs1

Reputation: 23

x="any string coming from db[090876]"
word_ends=True
num_groups=[]
num=''
for i in x:

    try:
          int(i)
          num+=i
          word_ends=False

    except:

          if word_ends == False:
          num_groups.append(num)
          num=''
          word_ends=True

Upvotes: 1

root
root

Reputation: 80386

In [74]: import re

In [75]: re.findall('\d+',"any string coming from db[090876]")
Out[75]: ['090876']

or digits only between parens with db before it to be safe:

In [76]: re.findall('db\[(\d+)\]',"any string coming from db[090876]")
Out[76]: ['090876']

Upvotes: 4

Related Questions