从Python中的字符串中提取值?

时间:2012-04-23 01:02:13

标签: python string

我想处理2个案例:

  1. (string) - > string

  2. @string otherStuff - > string

  3. 怎么做?

3 个答案:

答案 0 :(得分:2)

>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '(string)').groups()
('string', None)
>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '@string otherStuff').groups()
(None, 'string')

答案 1 :(得分:1)

import re

def getstring(string):
    testforstring = re.search("\((.*)\)",string)
    if testforstring:
        return testforstring.group(1)
    testforstring = re.search("@(.*?)\s+.*",string)
    if testforstring:
        return testforstring.group(1)
    return None

允许您这样做:

>>> print getstring('(hello)')
hello
>>> print getstring('@hello sdfdsf')
hello

答案 2 :(得分:0)

这对你有用吗?

In [45]: s='(string)' 
In [46]: s = s[1:-1]

In [47]: s
Out[47]: 'string'

In [48]: s = '@string otherstuff'
In [49]: s=' '.join(s.split()[1:])  

In [50]: s
Out[51]: 'otherstuff'