【问题标题】: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]在 Python 中,如果您返回一个字符串,它将在其周围显示引号,但如果您打印该字符串,它将不会以引号显示。为什么? [复制]
【发布时间】:2020-02-20 10:01:27
【问题描述】:

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

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

【问题讨论】:

    标签: python string printing quotes prompt


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      return 函数保存字符串的值,该值就是字符串。 print 函数不保存该值,它删除前导和尾随的字符串引号,然后在屏幕上显示该值。

      例如, 检查python的(strip函数),它有助于删除前导和尾随值

      【讨论】:

        猜你喜欢
        • 2023-02-17
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 2012-10-20
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 2017-04-18
        相关资源
        最近更新 更多