How do I print a variable inside quotes?
I would like to print the variable in quotes. I want to print"variable"
I tried a lot, which worked:
'"', variable", '"'
- but then I have two spaces in the output ->" variable "
When I do print '"'variable'"'
without comma, I get a syntax error.
How can I print something in a pair of quotes?
source to share
If the apostrophes ("single quotes") are ok, then the simplest way is:
print repr(str(variable))
Otherwise, prefer method .format
over operator %
(see Hackaholic's answer).
The operator %
(see Bhargav Rao's answer) also works even in Python 3 so far, but is intended to be removed in some future version.
The advantage of using it repr()
is that quotes within a string will be handled appropriately. If you have an apostrophe in the text, repr()
switch to ""
quotes. It will always create what Python recognizes as a string constant.
Whether this is good for your UI, well, that's another matter. With %
or, .format
you get a brief description of the way you could do this, starting with:
print '"' + str(variable) + '"'
... as Charles Duffy mentioned in a comment.
source to share
There are two easy ways to do this. First, just use a backslash in front of each quote mark, e.g .:
s = "\"variable\""
Another way is to have double quotes surrounding the string, use single single quotes, and Python will recognize them as part of the string (and vice versa):
s = '"variable"'
source to share