How to print variable inside quotation marks? [closed]

夙愿已清 提交于 2019-11-27 04:39:17

问题


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

I have tried a lot, what worked was: '"', variable", '"' – but then I have two spaces in the output -> " variable "

When I do print '"'variable'"' without the comma I get a syntax error.

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


回答1:


you can use format:

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

Learn about format here:Format




回答2:


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.




回答3:


Simply do:

print '"A word that needs quotation marks"'

Or you can use a triple quoted string:

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



回答4:


There are two simple ways to do this. The first is to just use a backslash before each quotation mark, like so:

s = "\"variable\""

The other way is, if there're double quotation marks surrounding the string, use single single quotes, and Python will recognize those as a part of the string (and vice versa):

s = '"variable"'



回答5:


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"


来源:https://stackoverflow.com/questions/27757133/how-to-print-variable-inside-quotation-marks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!