How do I make an f-string distinguish between an integer and a string?

Viewed 64

both

x = 1
f"{x}"

and

x = '1'
f"{x}"

give

'1'

as output. How do I get "1" and "'1'" as output?

2 Answers

Use the !r modifier to get the objects repr instead of its str:

f"{x!r}"

if you want to get the specific output to read:
"'1'" (text with quotes) and
"1" (text without quotes)
you can use:

f"{x}"     #text without single quotes
f"'{x}'"   #text with single quotes

this only works when you alternate quotes. like this: " ' ' " , ' " " '

f'"{x}"'

results in: '"1"' as output

Related