Skip to main content
 首页 » 编程设计

python之将括号内的数字解析为负数

2025年05月04日1298°冷暖

如何将字符串列表中带括号的数字解析为负数(或带负号的字符串)。

例子

input   
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']   
 
output   
['abcd',-1234,'Level-2 (2):','-31%', 'others','-3102.2%'] 

只在括号内包含数字或在括号内包含逗号/点且后跟百分比 (%) 符号的字符串应该被解析。不应解析其他字符串,例如 'Level-2 (2):'。

我试过了

translator = str.maketrans(dict.fromkeys('(),')) 
['-'+(x.translate(translator)) for x in list1] 

但输出是(每个元素都有一个 - 附加)

['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%'] 

请您参考如下方法:

你可以尝试使用re.sub,例如:

import re 
 
list1 = ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%'] 
res = [re.sub(r'^\(([\d+.,]+)\)(%?)$', r'-\1\2', el) for el in list1]  
# ['abcd', '-1,234', 'Level-2 (2):', '-31%', 'others', '-3,102.2%']