stellar
stellar

Reputation: 53

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?

Upvotes: 0

Views: 69

Answers (1)

Eugene Yarmash
Eugene Yarmash

Reputation: 149963

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}"}')

Upvotes: 4

Related Questions