Python PEP8 printing wrapped strings without indent

一世执手 提交于 2019-12-09 14:59:58

问题


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?


回答1:


Use automatic string concatenation + implicit line continuation:

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


>>> long_string
'Line 1 Line 2 Line 3 '



回答2:


This works:

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

Although I'd lay it out like this:

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

(So I start a new line when there's a \n in the string, as well as when I need to word wrap the source code.)




回答3:


try this:

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


来源:https://stackoverflow.com/questions/1302364/python-pep8-printing-wrapped-strings-without-indent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!