在Python中从字符串中提取字母数字子串
我在Python里有一个字符串
text = '(b)'
我想提取出其中的'b'。虽然我可以去掉字符串的第一个和最后一个字母,但我不想这么做,因为这个字符串可能包含像'(a)'、'(iii)'、'i)'、'(1'或'(2)'这样的内容。有时候它们根本没有括号,但里面总会有字母和数字的组合。我同样想提取出这些字母和数字的组合。
这个操作需要用一行代码来完成,因为我会在多个场合反复使用这个值。
在Python中,最好的方法是什么呢?
相关问题:
4 个回答
0
re.match(r'\(?([a-zA-Z0-9]+)', text).group(1)
根据你提供的示例输入,它会是:
>>> a=['(a)', '(iii)', 'i)', '(1' , '(2)']
>>> [ re.match(r'\(?([a-zA-Z0-9]+)', text).group(1) for text in a ]
['a', 'iii', 'i', '1', '2']
2
这段代码虽然不复杂,但它很通用。
>>> import string
>>> ''.join(i for i in text if i in string.ascii_letters+'0123456789')
它可以处理字符串中间各种组合的括号情况,而且如果字符串里还有其他非字母数字的字符(除了括号)也没问题。
4
我觉得这里不需要用正则表达式。你可以直接用 str.strip 来去掉任何括号:
>>> text = '(b)'
>>> text.strip('()')
'b'
>>> text = '(iii)'
>>> text.strip('()')
'iii'
>>> text = 'i)'
>>> text.strip('()')
'i'
>>> text = '(1'
>>> text.strip('()')
'1'
>>> text = '(2)'
>>> text.strip('()')
'2'
>>> text = 'a'
>>> text.strip('()')
'a'
>>>
关于 @MikeMcKerns 的评论,一个更稳妥的办法是把 string.punctuation 传给 str.strip:
>>> from string import punctuation
>>> punctuation # Just to demonstrate
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>>
>>> text = '*(ab2**)'
>>> text.strip(punctuation)
'ab2'
>>>
2
你可以通过Python的re模块来实现这个功能。
>>> import re
>>> text = '(5a)'
>>> match = re.search(r'\(?([0-9A-Za-z]+)\)?', text)
>>> match.group(1)
'5a'
>>> text = '*(ab2**)'
>>> match = re.search(r'\(?([0-9A-Za-z]+)\)?', text)
>>> match.group(1)
'ab2'