In Python interpreter, return without “ ' ”

点点圈 提交于 2019-11-26 22:45:40

In the Python interactive prompt, if you return a string, it will be displayed with quotes around it, mainly so that you know it's a string.

If you just print the string, it will not be shown with quotes (unless the string has quotes in it).

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

If you actually do need to remove leading/trailing quotation marks, use the .strip method of the string to remove single and/or double quotes:

>>> print("""'"hello"'""")
'"hello"'
>>> print("""'"hello"'""".strip('"\''))
hello

Here's one way that will remove all the single quotes in a string.

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

Here's another alternative that will remove the first and last character.

def remove2(x):
    return x[1:-1]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!