In Python interpreter, return without " ' "

user176073 picture user176073 · Sep 27, 2009 · Viewed 77.3k times · Source

In Python, how do you return a variable like:

function(x):
   return x

Without the 'x' (') being around the x?

Answer

Mark Rushakoff picture Mark Rushakoff · Sep 27, 2009

In the Python interactive prompt, if you return a string, it will be displayed with quotes around it, mainly so that you know it's a string.

If you just print the string, it will not be shown with quotes (unless the string has quotes in it).

>>> 1 # just a number, so no quotes
1
>>> "hi" # just a string, displayed with quotes
'hi'
>>> print("hi") # being *printed* to the screen, so do not show quotes
hi
>>> "'hello'" # string with embedded single quotes
"'hello'"
>>> print("'hello'") # *printing* a string with embedded single quotes
'hello'

If you actually do need to remove leading/trailing quotation marks, use the .strip method of the string to remove single and/or double quotes:

>>> print("""'"hello"'""")
'"hello"'
>>> print("""'"hello"'""".strip('"\''))
hello