Reputation: 113
I want to print the following using an f string literal. It will be running wihtin a function and apples will be one of the arguments. I want it to have the square brackets included.
"I like [apples] because they are green"
I have tried the following code:
"I like {} because they are green".format("apples")
The code above prints:
I like apples because they are green
How do I insert the square brackets [ ] or another special character such as < > into the f string literal?
Upvotes: 0
Views: 18545
Reputation: 61
To print: Hello {world}, how are you
where world is a variable
var1 = world
print(f"Hello {{var1}}, how are you")
is not correct. You have to add one extra bracket
var1 = world
print(f"Hello {{{var1}}}, how are you")
since in f-string double brackets plots a single bracket
Upvotes: 1
Reputation: 11
Here are few suggestions on how to use special characters in f-string.
Hello "world", how are you
var1 = "world"
print(f"Hello \"{var1}\", how are you")
Hello {world}, how are you
where world is a variable
var1 = world
print(f"Hello {{var1}}, how are you")
Hello {world}, how are you
where world is a constant
print(f"Hello ""{world""}, how are you")
Upvotes: 1
Reputation: 146
There are a couple possible ways to do this:
"I like [{}] because they are green".format("apples")
or
"I like {} because they are green".format("[apples]")
.
If instead of brackets you wanted to use actual special characters, you would just have to escape in the appropriate place:
"I like {} because they are green".format("\"apples\"").
Additionally, if you wanted to use actual f-strings, you could do the same thing as above but with the format:
f"I like {'[apples]'} because they are green"
but make sure to switch from double quotes to single quotes inside the brackets to avoid causing troubles by ending your string early.
Upvotes: 2