CAUTIOUS
Assuming a
, b
, and c
are variables. You can use locals()
function to get all the varibales in the local scope
. Calling locals()
function returns a dict
, where name of the varibale is key
and data stored in the variable is value
.
I would highly recommend not to use this approach. Rather store, a
, b
, and c
in a dict
as shown by @OneCricketeer in his solution.
But, if you still need to go with using variables, here is the code.
a = 1
b = 2
c = 3
a_list = ["ab", "abc", "ac", "b"]
for item in a_list:
add = 0
for sub_char in item:
add += locals()[sub_char]
print('+'.join(item), '=', add)
Output:
a+b = 3
a+b+c = 6
a+c = 4
b = 2
solved Sum of string elements of python list [closed]