Home > Blockchain >  How to print out variable name instead of value?
How to print out variable name instead of value?

Time:11-28

If I have a list of variables and each variable is assigned to an equation, how can I print the variable itself from the list not the result of the equation

For example:

x = 1   1
y = 2   2
z = 3   3

list = [x, y, z]

print(list[0])
print(list[1])
print(list[2])

Should print out:

x
y
z

Instead of:

2
4
6

CodePudding user response:

print() giving you a values of list[0], or list[1] or list[2] You gave them values 2,4,6 at the start of your app

x = 1   1
y = 2   2
z = 3   3

if you want to get x,y,z try this:

x = "x"
y = "y"
z = "z"

CodePudding user response:

in that case, you will need to change your list to a string, otherwise it will think that it is a variable and print the value assigned to it. to fix this you change line 5 to : list = ["x","y","z"] -> this way it will print out the string, not the value of the variable x

CodePudding user response:

The answers here are obviously correct, but perhaps they miss the real point. I presume you want to be able to show/use both the names and the values, for instance print something like "the sum of x, y, z is 12".

If this is the case you may want to work with Python's builtin namespaces, but the simplest thing is to use a dictionary where your names will be the keys and your values... well, the values:

my_dict = {}
my_dict['x'] = 1   1
my_dict['y'] = 2   2
my_dict['z'] = 3   3

','.join(my_dict.keys()) #'x,y,z'
sum(my_dict.values()) # 12

CodePudding user response:

From your first question i didn't understand well what do you need

I think this can work:

def dna_content(seq):
    A = ["A", (seq.count("A") / len(seq)) * 100]

    T = ["T", (seq.count("T") / len(seq)) * 100]
    G = ["G", (seq.count("G") / len(seq)) * 100]
    C = ["C", (seq.count("C") / len(seq)) * 100]
    bases = [A, T, G, C]
    for i in bases:
        print(str(i[0])   " content is: "   str(i[1]))

And... i couldn't find how to acces name of variable through it's value

UPD:

try this:

x = 1   1
y = 2   2
z = 3   3
list = ["x", "y", "z"]


for i in list:
    print(i, globals()[i])
  • Related