0

I have three variables

a = 1
b = 2
c = 3

and I want to have a string like 'a=1, b=2, c=3'

so, I use f-string,

x = ''
for i in [a, b, c]:
   x += f"{i=}"

but it gives,

x
'i=1, i=2, i=3, '

how do I make the i to be a, b, and c?

apostofes
  • 2,959
  • 5
  • 16
  • 31
  • Do you want the output to look like `'a=1, b=2, c=3, '`? – CoffeeTableEspresso Oct 06 '22 at 14:01
  • yes the last ', ' will have to be excluded – apostofes Oct 06 '22 at 14:03
  • There is a concept from lambda calculus called alpha conversion, which states the seemingly trivial property that something like `x = 3` and `y = 3` are equivalent, as long as you replace *all* uses of `x` in the same scope with `y`. If you cannot apply alpha conversion to a variable name because the name is important as *data*, then you probably don't want a variable, but an entry in a `dict` instead. – chepner Oct 06 '22 at 14:12
  • i have added an option to avoid using globals if you prefer – Lucas M. Uriarte Oct 06 '22 at 14:53
  • The `f'{variablename=}` trick (see [f-strings support = for self-documenting expressions and debugging](https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging)) requires the exact variable name. You cannot do what you want using this syntax. – Steven Rumbalski Oct 06 '22 at 15:06
  • What's wrong with doing `f'{a=}, {b=}, {c=}'`? – Steven Rumbalski Oct 06 '22 at 15:09

3 Answers3

4

The list [a, b, c] is indistiguishable from the list [1, 2, 3] -- the variables themselves are not placed in the list, their values are, so there is no way to get the variable names out of the list after you've created it.

If you want the strings a, b, c, you need to iterate over those strings, not the results of evaluating those variables:

>>> ', '.join(f"i={i}" for i in "abc")
'i=a, i=b, i=c'

If you want to get the values held by the variables with those names, you can do this by looking them up in the globals() dict:

>>> a, b, c = 1, 2, 3
>>> ', '.join(f"{var}={globals()[var]}" for var in "abc")
'a=1, b=2, c=3'

but code that involves looking things up in globals() is going to be really annoying to debug the first time something goes wrong with it. Any time you have a collection of named values that you want to iterate over, it's better to just put those values in their own dict instead of making them individual variables:

>>> d = dict(a=1, b=2, c=3)
>>> ', '.join(f"{var}={val}" for var, val in d.items())
'a=1, b=2, c=3'
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

A list doesn't remember the names of variables assigned to it. For that, you need a dictionary.

x = ""
my_dict = {'a': a, 'b': b, 'c': c}
for k, v in my_dict.items():
    x += f"{k}={v}, "
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • I did this, but I do not want repetition like `'a': a` – apostofes Oct 06 '22 at 14:04
  • 1
    Your program can't "see" the names of the variables; if you want to use them, you need to provide them explicitly. (Taking a step back, you may want `my_dict` instead of three separate variables in the first place.) – chepner Oct 06 '22 at 14:07
0

Using gloabls is not always a good idea if you want a solution that aovid using them you can inspect the variables that are declare using inspect module, there is thread regarding the getting the name of varibles here, from were the I took the function.

import inspect

def retrieve_var(var):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]

and now you can use a loop as similar to that you where using

a, b, c = 1, 2, 3

x = ''

for i in [a, b, c]:
    var = retrieve_var(i)
    x += f"{var[0]}={i}, "
Lucas M. Uriarte
  • 2,403
  • 5
  • 19