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?

+3


source to share


5 answers


you can use format

:

>>> s='hello'
>>> print '"{}"'.format(s)
"hello"

      



More about the format here: Format

+14


source


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.

+3


source


format

is the best. These are alternatives.

>>> s='hello'       # Used widly in python2, might get deprecated
>>> print '"%s"'%(s)
"hello"

>>> print '"',s,'"' # Usin inbuilt , technique of print func
" hello "

>>> print '"'+s+'"' # Very old fashioned and stupid way
"hello"

      

+2


source


Just do:

print '"A word that needs quotation marks"'

      

Or you can use a triple-quoted string:

print( """ "something" """ )

      

+1


source


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

      

+1


source







All Articles