【问题标题】:The difference between these 2 strings?这两个字符串之间的区别?
【发布时间】:2016-08-06 02:57:19
【问题描述】:

我最近开始学习 Python,我希望你能帮助我解决一个困扰我的问题。我一直在使用Learn Python The Hard Way 在线学习 Python。在练习 6 中,我遇到了一个问题,我在使用 %r 字符串格式化操作时会产生两个不同的字符串。当我打印一个字符串时,我得到了带有单引号的字符串 (' ')。另一个我得到双引号(" ")。

代码如下:

x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)

print "I said: %r." % x
print "I also said: %r." % y

第一个打印语句的结果:

I said: 'There are 10 types of people.'.

第二个打印语句的结果:

I also said: "Those who know binary and those who don't.".

我想知道为什么其中一个语句的结果带有单引号 (' ') 而另一个带有 (" ")。 ] 附:我正在使用 Python 2.7。

【问题讨论】:

    标签: python string printing string-formatting


    【解决方案1】:

    %r 正在获取repr 版本的字符串:

    >>> x = 'here'
    >>> print repr(x)
    'here'
    

    你看,单引号是通常使用的。但是,对于y,字符串中有一个单引号(撇号)。好吧,一个对象的repr 通常被定义,以便将其作为代码评估等于原始对象。如果 Python 使用单引号,则会导致错误:

    >>> x = 'those who don't'
      File "<stdin>", line 1
        x = 'those who don't'
                       ^
    SyntaxError: invalid syntax
    

    所以它使用双引号代替。

    【讨论】:

      【解决方案2】:

      注意这一行 -> do_not = "don't"。这个字符串中有一个单引号,这意味着单引号必须被转义;否则解释器会在哪里知道字符串开始结束的位置? Python 知道使用"" 来表示这个字符串文字。

      如果我们删除',那么我们可以期望在字符串周围有一个单引号:

      do_not = "dont"

      &gt;&gt;&gt; I also said: 'Those who know binary and those who dont.'.

      Single vs. double quotes in python.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-18
        • 2013-07-28
        • 1970-01-01
        • 1970-01-01
        • 2020-12-25
        • 1970-01-01
        • 2013-02-04
        • 2011-08-22
        相关资源
        最近更新 更多