'F String With Special Characters
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?
Solution 1:[1]
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.
Solution 2:[2]
Here are few suggestions on how to use special characters in f-string.
- If you want to print
Hello "world", how are you
var1 = "world"
print(f"Hello \"{var1}\", how are you")
- To print:
Hello {world}, how are you
where world is a variable
var1 = world
print(f"Hello {{var1}}, how are you")
- To print:
Hello {world}, how are you
where world is a constant
print(f"Hello ""{world""}, how are you")
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | my name |
Solution 2 | D Dhaliwal |
Solution 3 | Daniele Diodati |