Python f-string null format specifier

Viewed 177

Is there a way to specify a "null" formatter in the Python f-strings?

Python 3.8 introduced the '=' specifier in f-strings. The code:

n = 42
s = f'My favourite number is stored in variable {n=}'
print(s)

will print My favourite number is stored in variable n=42.

Is there a way for f-strings to use only the variable, and not the value? I would like to print My favourite number is stored in variable n.

I know this may seem silly, and that there are other ways to achieve this results (for instance, I could process the f-string with a regular expression to remove the undesired part). But I am still wondering if this is currently possible with regular f-strings.

Since f-strings implementation have a way to know the variable (and not only the value), it would seem logical that they had the option to render only the variable.

2 Answers
n = 42
s = f'My favourite number is stored in variable {n=}'.split('=')[0]
print(s)

Output: My favorite number is stored in variable n

EDIT -> Alternative: If you would like to use {var=} more than once in your f-string and assuming you do not want to use the = character anywhere else in the string you can use it as a delimiter on both sides of your variable.

s = f'My favourite number is stored in variable {n=}= or {m=}='
s = s.split('=')

j = 0
for i in s:
    print(list(s)[j], end='')
    j += 2
    if j >= len(s):
        break

This solution is not valid if you do intend to use the = character in your string for anything other than delimiter, however, it's the simplest one I found that matches the example you provided. If that does not match your use case please reference @Fzovpec's solution.

I don't know why you wanna use this implementation.

Way 1

print('My favourite number is stored in variable n')

Way 2

Otherwise, u should write much more code

n = 42

variables = {'n': n}
location = list(variables.keys())[list(variables.values()).index(n)]
s = f'My favourite number is stored in variable {location}'

print(s)
Related