我有一段文字:
没有你那张聪明的嘴,我该怎么办?
拉我进去,你
把我踢出去你让我 头晕目眩,别开玩笑了,我不能把你
固定在那个美丽的头脑里发生了什么
我在你神奇的神秘之旅中
我很头晕,不要不知道是什么打击了我,但我会没事的
...现在我想用这个文本创建一个字符串。例如在 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 "
Run Code Online (Sandbox Code Playgroud)
但是 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"""
Run Code Online (Sandbox Code Playgroud)
正如文档所解释的:
字符串文字可以跨越多行。一种方法是使用三引号:
"""..."""或'''...'''。行尾自动包含在字符串中 [...]
\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"
Run Code Online (Sandbox Code Playgroud)