在Python解释器中,如何返回一个没有单引号包围的值?

25
在Python解释器中,如何返回一个没有单引号包围的值? 例如:
>>> def function(x):
...     return x
...
>>> function("hi")
'hi'

我希望它返回的是hi而不是'hi'

2个回答

48

在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

2

以下是一种方法,可以去除字符串中的所有单引号。

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

这里有另一种选择,可以去除第一个和最后一个字符。
def remove2(x):
    return x[1:-1]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接