如何在Python中创建带换行符的字符串?

如何在Python中创建带换行符的字符串?,python,string,Python,String,我有一段文字: 没有你聪明的嘴我怎么办? 把我拉进来,你却把我踢出去 你让我头晕目眩,不是开玩笑,我不能把你牵制住 在那个美丽的心灵里发生了什么 我在你神奇的神秘之旅上 我头晕目眩,不知道是什么打击了我,但我会没事的 …现在我想用这个文本创建一个字符串。例如,在Python中: string = " What would I do without your smart mouth? Drawing me in, and you kicking me out You've got my head

我有一段文字:

没有你聪明的嘴我怎么办?
把我拉进来,你却把我踢出去
你让我头晕目眩,不是开玩笑,我不能把你牵制住
在那个美丽的心灵里发生了什么
我在你神奇的神秘之旅上
我头晕目眩,不知道是什么打击了我,但我会没事的

…现在我想用这个文本创建一个字符串。例如,在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并不认为这是字符串,因为它包含断线。如何将此文本设置为字符串?

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

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"""
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"
如下所述:

字符串文字可以跨多行。一种方法是使用三个引号:
“…”
“…”
。行尾自动包含在字符串[…]

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

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"""
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"

最简单的方法是将其引用三倍:

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'''
通过以下代码行:



输出与上述代码行相同:

还有其他方法吗?(我这样问,因为你说这是最简单的方法,这意味着可能还有其他方法)顺便说一句,我是数学家..哈哈
value = 'String\nString\nString'
value = "String\nString\nString"
>>> print value
String
String
String