Search code examples
pythonlist-comprehensionf-string

List comprehension using f-strings


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?


Solution

  • 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'