How to declare a long string in Python?

Python

Python Problem Overview


I have a really long string in python:

long_string = '
this is a really
really
really
long
string
'

However, since the string spans multiple lines, python doesn't recognize this as a string. How do I fix this?

Python Solutions


Solution 1 - Python

You can also do this, which is nice because you have better control over the whitespace inside of the string:

long_string = (
    'Lorem ipsum dolor sit amet, consectetur adipisicing elit, '
    'sed do eiusmod tempor incididunt ut labore et dolore magna '
    'aliqua. Ut enim ad minim veniam, quis nostrud exercitation '
    'ullamco laboris nisi ut aliquip ex ea commodo consequat. '
    'Duis aute irure dolor in reprehenderit in voluptate velit '
    'esse cillum dolore eu fugiat nulla pariatur. Excepteur sint '
    'occaecat cupidatat non proident, sunt in culpa qui officia '
    'deserunt mollit anim id est laborum.'
)

Solution 2 - Python

long_string = '''
this is a really
really
really
long
string
'''

""" does the same thing.

Solution 3 - Python

You can use either

long_string = 'fooo' \
'this is really long' \
'string'

or if you need linebreaks

long_string_that_has_linebreaks = '''foo
this is really long
'''

Solution 4 - Python

I was also able to make it work like this.

long_string = '\
this is a really \
really \
really \
long \
string\
'

I can't find any online references to this way of constructing a multi-line string. I don't know if it's correct. My suspicion is that python is ignoring the newline because of the backslash? Maybe someone can shed light on this.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuperStringView Question on Stackoverflow
Solution 1 - PythonFogleBirdView Answer on Stackoverflow
Solution 2 - PythonnmichaelsView Answer on Stackoverflow
Solution 3 - PythonplaesView Answer on Stackoverflow
Solution 4 - PythonShun Y.View Answer on Stackoverflow