An alternative is to use the new Advanced String Formatting
>>> example = "%{test}%".format(test="name")
>>> print example
%name%
Answer from Peter Hoffmann on Stack OverflowAn alternative is to use the new Advanced String Formatting
>>> example = "%{test}%".format(test="name")
>>> print example
%name%
example = "%%%(test)s%%" % {'test':'name',}
print example
%(key)s is a placeholder for a string identified by key. %% escapes % when using the % operator.
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.
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")
Here you go, Python documentation on old string formatting. tutorial -> 7.1.1. Old String Formatting -> "More information can be found in the [link] section".
Note that you should start using the new string formatting when possible.
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format