【问题标题】:How to create string with line breaks in Python? [duplicate]如何在 Python 中创建带换行符的字符串? [复制]
【发布时间】:2019-01-05 05:21:05
【问题描述】:

我有一条短信:

没有你聪明的嘴我该怎么办?
把我拉进来,你把我踢出去
你让我头晕目眩,不开玩笑,我不能把你固定下来
那美丽的心灵里发生了什么
我在你神奇的神秘之旅
而且我很头晕,不知道是什么击中了我,但我会没事的

...现在我想用这个文本创建一个字符串。例如在 Python 中:

string = " What would I do without your smart mouth?
Drawing me in, and you kicking me out
You've got my head spinning, no kidding, I can't pin you down
What's going on in that beautiful mind
I'm on your magical mystery ride
And I'm so dizzy, don't know what hit me, but I'll be alright "

但 Python 并不认为这是字符串,因为它包含换行符。我怎样才能把这个文本变成一个字符串?

【问题讨论】:

  • 创建多行字符串在三引号内包含多行字符串

标签: python string


【解决方案1】:

使用三引号

您可以使用三引号("""''')来分配带换行符的字符串:

string = """What would I do without your smart mouth?
Drawing me in, and you kicking me out
You've got my head spinning, no kidding, I can't pin you down
What's going on in that beautiful mind
I'm on your magical mystery ride
And I'm so dizzy, don't know what hit me, but I'll be alright"""

正如the documentation所解释的:

字符串字面量可以跨越多行。一种方法是使用三引号:"""..."""'''...'''。行尾自动包含在字符串中 [...]

使用\n

您还可以在字符串中显式使用换行符 (\n) 来创建换行符:

string = "What would I do without your smart mouth?\nDrawing me in, and you kicking me out\nYou've got my head spinning, no kidding, I can't pin you down\nWhat's going on in that beautiful mind\nI'm on your magical mystery ride\nAnd I'm so dizzy, don't know what hit me, but I'll be alright"

【讨论】:

    【解决方案2】:

    最简单的方法是三引号:

    string = '''What would I do without your smart mouth?
    Drawing me in, and you kicking me out
    You've got my head spinning, no kidding, I can't pin you down
    What's going on in that beautiful mind
    I'm on your magical mystery ride
    And I'm so dizzy, don't know what hit me, but I'll be alright'''
    

    【讨论】:

    • 还有其他方法吗? (我这样问,因为你说这是最简单的方法,这意味着可能存在其他方法来做到这一点)顺便说一句,我是一名数学家..lol
    【解决方案3】:

    通过以下代码行:

    value = '''
        String
        String
        String
        '''
    

    value = """
        String
        String
        String
        """
    

    value = 'String\nString\nString'
    

    value = "String\nString\nString"
    

    输出与上述代码行相同:

    >>> print value
    String
    String
    String
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 2011-01-25
      • 1970-01-01
      • 2011-05-05
      • 2012-07-20
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多