简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM