Guy Kovel
Guy Kovel

Reputation: 11

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)

Upvotes: 1

Views: 113

Answers (4)

Martijn Pieters
Martijn Pieters

Reputation: 1122322

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

Upvotes: 4

bozdoz
bozdoz

Reputation: 12860

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))

Upvotes: 2

speedingdeer
speedingdeer

Reputation: 1236

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

Upvotes: 0

xylon97
xylon97

Reputation: 274

print a[-2]

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

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

Upvotes: 1

Related Questions