How can I automatically wrap long python strings so that they print correctly?
Specifically, I am trying to add help strings with optparse which I want to be able to modify easily.
I have found several methods of dealing with long strings, none of which allow me to refill after making changes using M-q in emacs or similar:
p.add_option('-a', help = "this is my\
long help text")
forces newlines in the result and doesn't allow refilling
p.add_option('-a', help = "this is my "
"long help text")
formats correctly but doesn't allow refilling
p.add_option('-a', help = '''
this is my
long help text
''')
formats incorrectly but does allow refilling
p.add_option('-a', help = dedent('''
this is my
long help text
'''))
is the best option I've found, formats almost correctly and allows refilling but results in an additional space at the beginning of the string.
Use argparse instead of optparse, if you are using Python >= 2.7. It does dedent
for you. You can just do:
parser.add_argument('--argument', '-a', help='''
this is my
long help text
''')
Even if you are using Python < 2.7, you can install argparse from pypi.
Note that there is a way to suppress this auto-dedent behavior. The link given by @msw is actually the section about it.