Python textwrap Library - How to Preserve Line Breaks?

后端 未结 8 930
礼貌的吻别
礼貌的吻别 2021-02-04 02:19

When using Python\'s textwrap library, how can I turn this:

short line,

long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
         


        
8条回答
  •  鱼传尺愫
    2021-02-04 03:14

    I had to a similar problem formatting dynamically generated docstrings. I wanted to preserve the newlines put in place by hand and split any lines over a certain length. Reworking the answer by @far a bit, this solution worked for me. I only include it here for posterity:

    import textwrap
    
    wrapArgs = {'width': 90, 'break_long_words': True, 'replace_whitespace': False}
    fold = lambda line, wrapArgs: textwrap.fill(line, **wrapArgs)
    body = '\n'.join([fold(line, wrapArgs) for line in body.splitlines()])
    

提交回复
热议问题