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

How to create string with line breaks in Python?

本问题已经有最佳答案,请猛点这里访问。

我有一篇课文:

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
2
3
4
5
6
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
2
3
4
5
6
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 literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string [...]

使用

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

1
2
3
4
5
6
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"

通过以下代码行:

1
2
3
4
5
value = '''
    String
    String
    String
    '''
1
2
3
4
5
value ="""
    String
    String
    String
   """
1
2
3
value = 'String
String
String'
1
2
3
value ="String
String
String"

输出与上述代码行相同:

1
2
3
4
>>> print value
String
String
String


最简单的方法是三重引用:

1
2
3
4
5
6
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'''