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