1

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)

4

4 回答 4

4

您可以使用正则表达式(使用内置re模块):

import re

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

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

该模式匹配一​​个文字[字符,后跟 1 个或多个数字(\d转义表示数字字符组,+表示 1 个或多个),后跟一个文字]. 通过在部分周围加上括号\d+,我们创建了一个捕获组,我们可以通过调用.group(1)(“获取第一个捕获组结果”)来提取它。

结果:

>>> extract_num("auxiliary[0]")
0
>>> extract_num("foobar[42]")
42
于 2013-02-06T16:35:03.710 回答
2

我会使用正则表达式来获取数字。请参阅文档:http ://docs.python.org/2/library/re.html

就像是:

import re
def extract_num(s):
  m = re.search('\[(\d+)\]', s)
  return int(m.group(1))
于 2013-02-06T16:36:12.130 回答
1
print a[-2]

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

print a[a.index('[') + 1]
于 2013-02-06T16:36:56.363 回答
0
for number in re.findall(r'\[(\d+)\]',"auxiliary[0]"):
    do_sth(number)
于 2013-02-06T16:40:03.080 回答