Home > database >  Can string value in Python 3.8 short-handed f-string be without quotes?
Can string value in Python 3.8 short-handed f-string be without quotes?

Time:03-29

>>> long_variable_name = 'foo'
>>> f'long_variable_name={long_variable_name}'
'long_variable_name=foo'
>>> f'{long_variable_name=}'
"long_variable_name='foo'"

Is it possible to have the second short-handed expression f'{long_variable_name=}' produce the same output as the first expression? I.e. without the quotes for the string value.

CodePudding user response:

Looks like the {var=} syntax defaults to calling an object's __repr__, so you can explicitly declare it call an object's __str__, eg:

long_variable_name = 'foo'
f'{long_variable_name=!s}'

Gives you:

'long_variable_name=foo'
  • Related