在 Python 解释器中,如何返回没有单引号的值?
- 2025-02-28 08:23:00
- admin 原创
- 59
问题描述:
在 Python 解释器中,如何返回没有单引号的值?
例子:
>>> def function(x):
... return x
...
>>> function("hi")
'hi'
hi
我期望它能返回'hi'
解决方案 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
解决方案 2:
这是一种删除字符串中所有单引号的方法。
def remove(x):
return x.replace("'", "")
这是另一种删除第一个和最后一个字符的替代方法。
def remove2(x):
return x[1:-1]
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD