In Python if you return a string,it will be displayed with quotes around it but If you print the string, it will not be shown with quotes. why? [duplicate]

送分小仙女□ 提交于 2021-02-13 17:26:19

问题


In the Python interactive prompt, if you return a string, it will be displayed with quotes around it. But if you just print the string, it will not be shown with quotes. Why?

>>> a='world'
>>> a
'world'
>>> print(a)
world

回答1:


Simply put: The quotes allow python to treat whatever is inside of them as a 'string literal'; that way, if we wanted to write a string like 'print([0, 1, 2])' we would actually literally get print([0, 1, 2]) as a reply instead of [0, 1, 2]. The print function in python only prints the string literal out to the console for the user to see, since the user knows this is a string.

If we wanted to include quotes in the print, we could use a mixture of ' and " (single vs. double) quotes. For example, we could 'define' the string literal / tell python its going to be a literal with outer quotes "" then inside of that put 'testing...'. So if we set that equal to a variable for clarity (example = "'testing...'") now print(example), as you can see we would get the single quotes (') included in the output.




回答2:


return function holds the value of the string and that value is the string. print function doesn't hold the value, it removes the string quotes leading and trailing then displays the value on the screen.

as for example, check the (strip function) of python, it helps to remove leading and trailing values



来源:https://stackoverflow.com/questions/58534996/in-python-if-you-return-a-string-it-will-be-displayed-with-quotes-around-it-but

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