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.
CodePudding user response:
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
CodePudding user response:
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)