在Python解释器中,返回时不带“”

2024-04-19 22:34:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

function(x):
   return x

没有'x'')在x附近?


Tags: returnfunction
2条回答

这里有一种方法可以删除字符串中的所有单引号。

def remove(x):
    return x.replace("'", "")

这里有另一个选择,将删除第一个和最后一个字符。

def remove2(x):
    return x[1:-1]

在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

相关问题 更多 >