Andrew Chon Andrew Chon -4 years ago 69
Python Question

How Can I Turn Variables Into A String of Values

I don't know if this is possible (new to python), but I want to use a list of defined variables, and when I run in it shell or cmd to accept input then display the translated text.

For an example:

a = "00";
aa = " 0000";
b = "11";
bb =" 1111";
zz =" ";


Then if the client inputs: a,b,bb,aa,zz,a,b

I want it to display: 0011 1111 0000 0011
(just like that)

I would like to stick to the current way of assigning variables if there are other ways.

Answer Source

It is probably best to achieve this with a dictionary you define yourself. But if as you say, you don't want to change how you're working with those variables, you could also make use of locals() which gives you access to a dictionary of defined local variables. To give you a fully worked-out example:

a = "00"
aa = " 0000"
b = "11"
bb =" 1111"
zz =" "
variables = input("Variable string? ")
# Process the input into variable names
variables = [variable_.strip() for variable_ in variables.split(",")]
# Find values assigned to each variable
text = []
for variable_ in variables:
    try:
        text.append(str(locals()[variable_]))
    except KeyError:
        print("Variable {} not found".format(variable_))
print("".join(text))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download