在Python解释器中,返回没有"'"

15 python interpreter read-eval-print-loop

在Python中,如何返回变量,如:

function(x):
   return x
Run Code Online (Sandbox Code Playgroud)

没有'x'(')在周围x

Mar*_*off 31

在Python交互式提示符中,如果您返回一个字符串,它将在其周围显示引号,主要是为了让您知道它是一个字符串.

如果您只是打印字符串,它将不会显示引号(除非字符串中引号).

>>> 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'
Run Code Online (Sandbox Code Playgroud)

如果你真的需要去除前/后引号,使用.strip字符串的方法来删除单和/或双引号:

>>> print("""'"hello"'""")
'"hello"'
>>> print("""'"hello"'""".strip('"\''))
hello
Run Code Online (Sandbox Code Playgroud)