如何在 Python 中创建带换行符的字符串? [复制]

Posted

技术标签:

【中文标题】如何在 Python 中创建带换行符的字符串? [复制]【英文标题】:How to create string with line breaks in Python? [duplicate] 【发布时间】: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 并不认为这是字符串,因为它包含换行符。我怎样才能把这个文本变成一个字符串?

【问题讨论】:

创建多行字符串在三引号内包含多行字符串 【参考方案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

【讨论】:

以上是关于如何在 Python 中创建带换行符的字符串? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何在 QOpenGLTexture 中创建带 alpha 的纹理?

如何在 django 中创建带参数的链接

如何在 Android 中创建带圆角的 ListView?

如何在 Oracle 12c 中创建带条件的索引?

如何在React MUI中创建带标签的TextField

如何在 Swift 4 的 UIView 中创建带圆角的渐变边框