簡體   English   中英

從python中的字符串中提取字母數字子字符串

[英]Extracting alphanumeric substring from a string in python

我在python中有一個字符串

text = '(b)'

我想提取'b'。 我可以刪除字符串的第一個和最后一個字母,但我不這樣做的原因是因為文本字符串可能包含'(a)',(iii),'i)','(1'或'(2) '。有時它們根本沒有括號。但它們總是包含一個字母數字值。但我同樣想要檢索那里的字母數字值。

這個專長必須在一行代碼或代碼塊中完成,這些代碼或代碼塊只返回值,因為它將在多種情況下迭代使用

什么是python中最好的方法,

我不認為這里需要正則表達式。 你可以用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'
>>>

不花哨,但這很通用

>>> import string
>>> ''.join(i for i in text if i in string.ascii_letters+'0123456789')

這適用於字符串中間的所有種類的括號組合,以及如果您有其他非字母數字字符(括號內)。

re.match(r'\(?([a-zA-Z0-9]+)', text).group(1)

由exmple提供的輸入將是:

>>> 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']

你可以通過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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM