nahanarts
nahanarts

Reputation: 95

Wrapping lines in python: breaking on an argument string

I have a script in which a very long argument of type str is passed to a function:

parser = argparse.ArgumentParser(description='Auto-segments a text based on the TANGO algorithm (Rie Kubota Ando and Lillian Lee, "Mostly-Unsupervised Statistical Segmentation of Japanese Kanji Sequences" (Natural Language Engineering, 9(2):127-149, 2003)).')

I'd like to limit line length in this script to 79 chars, which means line breaking in the middle of the string in question. Simply wrapping at 79 yields something like this, which is syntactically ill-formed:

parser = argparse.ArgumentParser(description="Auto-segments a text based on 
    the TANGO algorithm (Rie Kubota Ando and Lillian Lee, 'Mostly-Unsupervis
    ed Statistical Segmentation of Japanese Kanji Sequences' (Natural Langua
    ge Engineering, 9(2):127-149, 2003)).")

PEP 8 has guidelines for breaking lines in various non-argument-string-internal locations, but is there a way to break the line in the middle of an argument string?

(Related but less important question: What is a sensible/conventional way to break natural language text mid-word inside a (python) script?)

Upvotes: 5

Views: 3191

Answers (3)

unutbu
unutbu

Reputation: 879671

argparse reformats the description string anyway, so it won't change the result if you use a multiline string with extra spaces:

import argparse

parser = argparse.ArgumentParser(description='''Auto-segments a text based on the
    TANGO algorithm (Rie Kubota Ando and Lillian Lee, "Mostly-Unsupervised
    Statistical Segmentation of Japanese Kanji Sequences" (Natural Language
    Engineering, 9(2):127-149, 2003)).''')

args = parser.parse_args()

% test.py -h

usage: test.py [-h]

Auto-segments a text based on the TANGO algorithm (Rie Kubota Ando and Lillian Lee,
"Mostly-Unsupervised Statistical Segmentation of Japanese Kanji Sequences" (Natural
Language Engineering, 9(2):127-149, 2003)).

optional arguments:
  -h, --help  show this help message and exit

Upvotes: 0

Eevee
Eevee

Reputation: 48546

Literal strings can appear next to each other, and will compile to a single string. Thus:

parser = argparse.ArgumentParser(description="Auto-segments a text based on "
    "the TANGO algorithm (Rie Kubota Ando and Lillian Lee, 'Mostly-Unsupervised "
    "Statistical Segmentation of Japanese Kanji Sequences' (Natural Language "
    "Engineering, 9(2):127-149, 2003)).")

Adjust as desired to fit in 80.

Upvotes: 5

Wei Yen
Wei Yen

Reputation: 350

>>>longarg = "ABCDEF\
GHIJKLMNOPQRSTUVW\
XYZ"

>>>print longarg
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Upvotes: 1

Related Questions