Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of writing a single-line long string

Tags:

python

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.

like image 757
Cyker Avatar asked Nov 28 '16 03:11

Cyker


People also ask

How do you write a long string in Python?

Use triple quotes to create a multiline string You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.

How do you break a long string line in Python?

Inserting a newline code \n , \r\n into a string will result in a line break at that location.

What is multiline string?

A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.

What is single line string in Python?

Whenever Python interpreter starts processing a string it looks for a quotation mark, it could either be a single quote or double quote. The opening quote indicates the starting of the string and closing quote indicates the end of the string.


2 Answers

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

like image 121
rgilligan Avatar answered Oct 06 '22 07:10

rgilligan


Here's the PEP8 guideline: https://www.python.org/dev/peps/pep-0008/#maximum-line-length

Wrap long lines in parenthesis.

Use a maximum of 72 characters per line for long lines of text.

If you have any operators in your string, place the line breaks before them.

Other than that, as long as you're not obscuring what's going on, it's pretty much up to you on how you want to do it.

like image 26
Denny Avatar answered Oct 06 '22 08:10

Denny