6

I have a text :

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

...now I want to create a string with this text. For example in 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 "

But Python didn't consider this as string as it contain line breaks. How can I make this text as a string?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Cloud JR K
  • 181
  • 1
  • 1
  • 7

3 Answers3

5

Using triple-quotes

You can use the triple-quotes (""" or ''') to assign a string with line breaks:

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

As explained by the documentation:

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string [...]

Using \n

You can also explicitly use the newline character (\n) inside your string to create line breaks:

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"
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
1

Through the following code lines:

value = '''
    String
    String
    String
    '''

value = """
    String
    String
    String
    """

value = 'String\nString\nString'

value = "String\nString\nString"

The output is same with above code lines:

>>> print value
String
String
String

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
0

The easiest way would be to triple-quote it:

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'''
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    Is there any other way to do it? (i ask like this coz you say that this is the easiest way,that means there may exists some other ways to do it ) btw i'm a mathematician..lol – Cloud JR K Jul 28 '18 at 07:00