Search code examples
pythonf-string

Why aren't strings allowed to be embedded into f-strings just as values?


print(f"my age is {54} and my name is {True}")

yields

my age is 54 and my name is True

and the following also works

print(f"my age is {54.0} and my name is {True}")

However, when I place a string inside the curly brackets:

print(f"my age is {54.0} and my name is {"Bill"}")

I get an Invalid Syntax error.

So how is the string data type different from other primitives in this instance?


Solution

  • It's not different, you just need to use a different type of quotes for the f-string itself and the string inside the placeholder:

    print(f'my age is {54.0} and my name is {"Bill"}')
    

    You can even nest f-strings using different quoting characters:

    print(f'{f"{123}"}')