【问题标题】:inverted comma and string in pythonpython中的倒逗号和字符串
【发布时间】:2010-09-07 10:29:59
【问题描述】:

我对 python 有点陌生,但我已经编写了许多程序,包括需要大量字符串操作的下载管理器、游戏和文本编辑器。
为了表示字符串文字,我使用单引号或双引号。当时我首先想到的那个。

虽然我还没有遇到任何麻烦。我的问题:python 是否允许两者兼有,或者仅仅是为了兼容性、可用性等?

【问题讨论】:

标签: python string literals


【解决方案1】:

"string"'string' 在 Python 中没有区别,因此,正如您所建议的,它只是为了可用性。

>>> 'string' == "string"
True

您还可以对多行​​字符串使用三引号:

>>> mystring = """Hello
... World!"""
>>> mystring
'Hello\nWorld!'

另一个技巧是自动连接相邻的字符串文字:

>>> mystring = "Hello" 'World!'
>>> mystring
'HelloWorld!'

还有string prefixes which you can read about in the documentation

【讨论】:

    【解决方案2】:

    这意味着您可以轻松地在其中包含 either 单引号或双引号的字符串,而无需任何转义字符。所以你可以这样做:

    a = 'The knights who say "ni!"'
    b = "We're knights of the Round Table, we dance whene'er we're able."
    

    【讨论】:

      【解决方案3】:

      只是为了兼容性和可用性。

      当您将其中一个嵌入到字符串中时,它有时会很有用,因此与'He says: "Hello"' 相比,我会使用"Who's there?"

      另一个选项当然是三引号字符串,比如

      """This is a long string that can contain single quotations like ' or ".
      It can also span multiple lines"""
      

      等于

      '''This is a long string that can contain single quotations like ' or ".
      It can also span multiple lines'''
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-26
        • 2018-05-20
        • 1970-01-01
        • 2023-01-04
        • 1970-01-01
        • 2015-05-31
        • 1970-01-01
        • 2021-03-21
        相关资源
        最近更新 更多