在Python解释器中如何返回没有单引号的值?

25 投票
2 回答
104988 浏览
提问于 2025-04-15 14:37

在Python的解释器中,怎么才能返回一个值,而不让它周围有单引号呢?

举个例子:

>>> def function(x):
...     return x
...
>>> function("hi")
'hi'

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

2 个回答

2

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

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

还有另一种方法可以去掉字符串的第一个和最后一个字符。

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

在Python的交互式提示符中,如果你返回一个字符串,它会用引号显示出来,这样你就能知道它是一个字符串。

如果你只是用print来输出这个字符串,它就不会带引号显示(除非这个字符串本身包含引号)。

>>> 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

撰写回答