在 Python 中,如何返回如下变量:
function(x):
return x
没有'x'
( '
) 在x
?
在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'
如果您确实需要删除前导/尾随引号,请使用.strip
字符串的方法删除单引号和/或双引号:
>>> print("""'"hello"'""")
'"hello"'
>>> print("""'"hello"'""".strip('"\''))
hello
这是删除字符串中所有单引号的一种方法。
def remove(x):
return x.replace("'", "")
这是另一个删除第一个和最后一个字符的替代方法。
def remove2(x):
return x[1:-1]