Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print variable inside quotation marks?

I would like to print a variable within quotation marks. I want to print out "variable"

I have tried a lot, what worked was:

print('"', variable, '"')

but then I have two spaces in the output:

" variable "

How can I print something within a pair of quotation marks?

like image 534
Heiko Avatar asked Jan 03 '15 16:01

Heiko


People also ask

How do you put a variable in a quote?

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape).

How do you print a variable within a quote in Python?

For Python, you might use '"' + str(variable) + '"' .

How do you print a string in a quote in Python?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.


2 Answers

you can use format:

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

Learn about format here:Format

In 3x you can use f:

>>> f'"{s}"'
'"hello"'
like image 69
Hackaholic Avatar answered Sep 21 '22 23:09

Hackaholic


If apostrophes ("single quotes") are okay, then the easiest way is to:

print repr(str(variable))

Otherwise, prefer the .format method over the % 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 to using repr() is that quotes within the string will be handled appropriately. If you have an apostrophe in the text, repr() will switch to "" quotes. It will always produce something that Python recognizes as a string constant.

Whether that's good for your user interface, well, that's another matter. With % or .format, you get a shorthand for the way you might have done it to begin with:

print '"' + str(variable) + '"'

...as mentioned by Charles Duffy in comment.

like image 39
Mike Housky Avatar answered Sep 22 '22 23:09

Mike Housky