简体   繁体   中英

Extracting a number from an unspaced string in Python

I need to extracted a number from an unspaced string that has the number in brakets for example:

"auxiliary[0]"

The only way I can think of is:

def extract_num(s):    
   s1=s.split["["]
   s2=s1[1].split["]"]
   return int(s2[0])

Which seems very clumsy, does any one know of a better way to do it? (The number is always in "[ ]" brakets)

You could use a regular expression (with the built-in re module ):

import re

bracketed_number = re.compile(r'\[(\d+)\]')

def extract_num(s):
    return int(bracketed_number.search(s).group(1))

The pattern matches a literal [ character, followed by 1 or more digits (the \\d escape signifies the digits character group, + means 1 or more), followed by a literal ] . By putting parenthesis around the \\d+ part, we create a capturing group, which we can extract by calling .group(1) ("get the first capturing group result").

Result:

>>> extract_num("auxiliary[0]")
0
>>> extract_num("foobar[42]")
42

I would use a regular expression to get the number. See docs: http://docs.python.org/2/library/re.html

Something like:

import re
def extract_num(s):
  m = re.search('\[(\d+)\]', s)
  return int(m.group(1))
print a[-2]

print a[a.index(']') - 1]

print a[a.index('[') + 1]
for number in re.findall(r'\[(\d+)\]',"auxiliary[0]"):
    do_sth(number)

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