Cyker Cyker - 5 days ago 6
Python Question

Pythonic way of writing a single-line long string

What is the Pythonic way of writing a single-line but long string in program:

s = 'This is a long long string.'


Additionally, the string may need to be formatted with variables:

s = 'This is a {} long long string.'.format('formatted')


Existing Solution 1



s = 'This is a long '\
'long '\
'string.'


Additional trailing
\
characters make reformatting very difficult. Joining two lines with a
\
gives an error.

Existing Solution 2



s = 'This is a long \
long \
string.'


Except for a similar problem as above, subsequent lines must be aligned at the very beginning, which gives awkward readability when the first line is indented.

Answer

For long strings where you don't want \n characters, use 'string literal concatenation':

s = (
    'this '
    'is '
    'a '
    'long '
    'string')

Output:

This is a long string

And it can be formatted as well:

s = (
    'this '
    'is '
    'a '
    '{} long '
    'string').format('formatted')

Output:

This is a formatted long string

Comments