Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create string with line breaks in Python? [duplicate]

Tags:

python

string

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?

like image 589
Cloud JR K Avatar asked Jul 28 '18 06:07

Cloud JR K


2 Answers

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"
like image 105
Ronan Boiteau Avatar answered Sep 23 '22 16:09

Ronan Boiteau


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

like image 28
Benyamin Jafari Avatar answered Sep 23 '22 16:09

Benyamin Jafari