如何编写用于计算带字母字符的数字的 Python 代码

How to write the Python code for calculating numbers with alphabet characters

我想创建 python 计算器解决 2a+3a , 3ab+5ab 之类的问题。我做了普通的计算器,但我想创建这种类型的计算器。怎么做?给我一些想法

假设您得到输入,

import re
s = "2a + 3b+ 4a +3bc"
input = [x.strip() for x in s.split('+')]

var_dict = {}
for inp in input:
    variable = ''.join(x for x in inp if x.isalpha())
    var_dict.setdefault(variable, []).append(int(re.search(r'\d+', inp).group()))

fin_str = []
for key,val in var_dict.iteritems():
    fin_str.append(str(sum(val)) + str(key))

puts ', '.join([str(x) for x in fin_str])

python 版本 2.7+