我有一条短信:
没有你的聪明嘴我该怎么办?
吸引我,你把我踢出去
你的头在旋转,没有开玩笑,我无法把你固定下来
那个美丽的心灵发生了什么
我在你神奇的神秘旅程中
而且我很头晕,不知道是什么打了我,但我会没事的
...现在我要使用此文本创建一个字符串。例如在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并不认为这是字符串,因为它包含换行符。如何使该文本成为字符串?
答案 0 :(得分: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"""
字符串文字可以跨越多行。一种方法是使用三引号:
中"""..."""
或'''...'''
。行尾自动包含在字符串[...]
\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"
答案 1 :(得分:1)
value = '''
String
String
String
'''
value = """
String
String
String
"""
value = 'String\nString\nString'
value = "String\nString\nString"
>>> print value
String
String
String
答案 2 :(得分:0)
最简单的方法是对它进行三重引用:
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'''