它会用引号括起来显示

它会用引号括起来显示

本文介绍了在 Python 中,如果你返回一个字符串,它会用引号括起来显示,但如果你打印字符串,它不会用引号显示.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 交互式提示中,如果您返回一个字符串,它将用引号括起来显示.但是如果你只是打印字符串,它不会用引号显示.为什么?

>>>一个='世界'>>>一个'世界'>>>打印(一)世界
解决方案

简单地说:引号允许 python 将它们内部的任何内容视为字符串文字";这样,如果我们想写一个像 'print([0, 1, 2])' 这样的字符串,我们实际上会得到 print([0, 1, 2]) 作为回复而不是[0, 1, 2].python 中的 print 函数只将字符串文字打印到控制台供用户查看,因为用户知道这是一个字符串.

如果我们想在打印中包含引号,我们可以混合使用 ' 和 "(单引号与双引号).例如,我们可以定义"字符串文字/告诉 python 它将是一个文字用外引号 "" 然后在里面放置 'testing...'.所以如果我们为了清楚起见将它设置为等于一个变量 (example = "'testing...'") 现在 print(example),如您所见,我们将获得包含在输出中的单引号 (').

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
解决方案

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.

这篇关于在 Python 中,如果你返回一个字符串,它会用引号括起来显示,但如果你打印字符串,它不会用引号显示.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 17:29