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

2024-02-24

我有一段文字:

没有你聪明的嘴我该怎么办?
把我拉进去,你又把我踢出去
你让我头晕目眩,别开玩笑了,我无法阻止你
那美丽的心灵里到底在想什么
我在你的神奇神秘旅程中
我很头晕,不知道是什么击中了我,但我会没事的

...现在我想用这个文本创建一个字符串。例如在 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 并不将其视为字符串,因为它包含换行符。我怎样才能把这个文本变成一个字符串?


使用三引号

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

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

正如所解释的文档 https://docs.python.org/3/tutorial/introduction.html:

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

Using \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"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐