【问题标题】:What is the difference in Python print with single (') and double (") quotation marks? [duplicate]单引号(')和双引号(“)的Python打印有什么区别? [重复]
【发布时间】:2015-05-09 02:01:40
【问题描述】:

这个问题可能是一个非常愚蠢的问题。在 Python 中使用单引号和双引号打印在技术上是否有任何区别。

print '1'
print "1"

它们产生相同的输出。但是在口译员级别上必须有所不同。哪个是最好的建议方法?

【问题讨论】:

  • 没有区别。最好的就是你喜欢的,所以这完全取决于个人喜好。
  • 我通常更喜欢单引号,因为它减少了一次按键操作,因为您不需要 shift 键。

标签: python syntax


【解决方案1】:

当使用print 函数和单引号括起来的字符串时,单引号需要转义字符,但双引号不需要;对于用双引号括起来的字符串,双引号需要转义字符,但单引号不需要:

print '\'hello\''
print '"hello"'
print "\"hello\""
print "'hello'"

如果你想同时使用单引号和双引号而不用担心转义字符,你可以用三个双引号或三个单引号打开和关闭字符串:

print """In this string, 'I' can "use" either."""
print '''Same 'with' "this" string!'''

【讨论】:

    【解决方案2】:

    相同:更多信息请参见 Python 文档:https://docs.python.org/3/tutorial/introduction.html

        3.1.2. Strings
        Besides numbers, Python can also manipulate strings, 
    which can be expressed in several ways. 
    They can be enclosed in single quotes ('...') or double quotes ("...") 
    with the same result [2]. \ can be used to escape quotes:
    

    打印函数省略了引号:

        In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. 
    While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. 
    The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. 
    The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters
    
    >>> '"Isn\'t," she said.'
    '"Isn\'t," she said.'
    >>> print('"Isn\'t," she said.')
    "Isn't," she said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 2016-06-10
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 2010-12-31
      • 2010-10-30
      相关资源
      最近更新 更多