Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PEP8 printing wrapped strings without indent

There is probably an easy answer for this, just not sure how to tease it out of my searches.

I adhere to PEP8 in my python code, and I'm currently using OptionParser for a script I'm writing. To prevent lines from going beyond a with of 80, I use the backslash where needed.

For example:

if __name__=='__main__':
    usage = '%prog [options]\nWithout any options, will display 10 random \
    users of each type.'
    parser = OptionParser(usage)

That indent after the backslash results in:

~$ ./er_usersearch -h
Usage: er_usersearch [options]
Without any options, will display 10 random     users of each type.

That gap after "random" bugs me. I could do:

 if __name__=='__main__':
    usage = '%prog [options]\nWithout any options, will display 10 random \
 users of each type.'
    parser = OptionParser(usage)

But that bugs me just as much. This seems silly:

 if __name__=='__main__':
    usage = ''.join(['%prog [options]\nWithout any options, will display',
                     ' 10 random users of each type.'])
    parser = OptionParser(usage)

There must be a better way?

like image 299
EMiller Avatar asked Aug 19 '09 20:08

EMiller


People also ask

How do you wrap a string in Python?

Wrap a string: wrap() , fill() Use '\n'. join(list) to get the string with the line feed code \n . The fill() function returns a string with line breaks, not a list. It is the same as '\n'.

How do you wrap around a line in Python?

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

How do you wrap text in idle Python?

Using parenthesized line breaksUsing Python's inferred line continuation within parentheses, brackets, and braces is the recommended method of wrapping lengthy lines.

Which of the following modules warn about pp8 inconsistencies present in Python script?

pep8 warn about 8-space indent.


1 Answers

Use automatic string concatenation + implicit line continuation:

long_string = ("Line 1 "
               "Line 2 "
               "Line 3 ")


>>> long_string
'Line 1 Line 2 Line 3 '
like image 104
Kenan Banks Avatar answered Sep 21 '22 13:09

Kenan Banks