我有一個類似于下面的字串串列:
l = ['ad2g3f234','4jafg32','fg23g523']
對于每個字串l,我想洗掉每一個數字(除了2和3他們是否出現23)。所以在這種情況下,我想要以下結果:
n = ['adgf23','jafg','fg23g23']
我該怎么做?我試過re.findall:
w = [re.findall(r'[a-zA-Z] ',t) for t in l]
但它沒有給出我想要的結果。
uj5u.com熱心網友回復:
一種方法是將字串替換兩次:
[re.sub("\d", "", i.replace("23", "*")).replace("*", "23") for i in l]
輸出:
['adgf23', 'jafg', 'fg23g23']
uj5u.com熱心網友回復:
在re.sub 中使用占位符
l = ['ad2g3f234','4jafg32','fg23g523']
w = [re.sub('#','23',re.sub('\d','',re.sub('23','#',t))) for t in l]
['adgf23', 'jafg', 'fg23g23']
編輯
正如克里斯回答的那樣,方法是相同的,盡管字串替換將是更好的替代 stack_comparison
uj5u.com熱心網友回復:
將 re.sub 與函式一起使用
進口重新
def replace(m):
if m.group() == '23':
return m.group()
else:
return ''
l = ['ad2g3f234','4jafg32','fg23g523']
w = [re.sub(r'23|\d', replace, x) for x in l]
#w: ['adgf23', 'jafg', 'fg23g23']
解釋
re.sub(r'23|\d', replace, x)
- checks first for 23, next for a digit
- replace function leaves alone match with 23
- changes match with digit to null string.
uj5u.com熱心網友回復:
您可以在一組中捕獲 23,并洗掉所有其他數字。在替換中,使用包含 23 的組(如果存在),否則替換為空字串。
import re
l = ['ad2g3f234', '4jafg32', 'fg23g523']
result = [
re.sub(
r"(23)|(?:(?!23)\d) ",
lambda m: m.group(1) if m.group(1) else "", s) for s in l
]
print(result)
輸出
['adgf23', 'jafg', 'fg23g23']
Python 演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/336635.html
上一篇:從字串中提取空格分隔的數字
