简体   繁体   English

在Python中,有没有一种方法可以插入换行符并在字符串的每68个字符之间插入空格?

[英]In Python, is there a way to insert a line break and spaces every 68 characters of a string?

I am reading in descriptions and converting them to strings in python. 我正在阅读说明,并将其转换为python中的字符串。 Due to outdated standards, the length of each line must be no more than 80 characters. 由于过时的标准,每行的长度不得超过80个字符。 The first 12 is a ';' 前12个是';' followed by 11 spaces and the last 68 should be the string. 后跟11个空格,最后68个字符串。

We have strings of over 300 characters, so I need to insert a '\\n;' 我们有超过300个字符的字符串,因此我需要插入'\\n;' and 11 spaces every 68 characters. 每68个字符11个空格。 We also have strings that already contain a '\\n' that needs to be maintained. 我们还具有已经包含需要维护的'\\n'字符串。 Also it would be prefered if words weren't broken up. 如果单词不被打断,那将是更可取的。

Is this possible in python? 这可能在python中吗?

I was attempting to do it like this but was having no luck. 我试图这样做,但没有运气。

def badChars(stri):
    p=0
    if len(stri) > 68:
        for i in range(0, len(stri)):
            if stri[i] == "\\" and stri[i+1] == "n":
                p=-1
            if p > 68:
                stri[i] = stri[i] + "\n;                 "
                p=-1
            p=p+1  

I need the words to stay intact and the current \\n to be maintained. 我需要保持原样并保持当前\\n的字样。

You can wrap lines using the textwrap module ; 您可以使用textwrap模块换行; you can specify indentation to be used too: 您也可以指定要使用的缩进:

import textwrap

indentation = ';' + ' ' * 11
result = textwrap.fill(
    input_text, width=80,
    initial_indent=indentation, subsequent_indent=indentation)

If you need to maintain existing newlines, split on those first, apply wrapping to each line, then rejoin with newlines: 如果需要维护现有的换行符,请先拆分这些换行符,然后将换行符应用于每行,然后重新加入换行符:

indentation = ';' + ' ' * 11
params = {
    'width': 80,
    'initial_indent': indentation,
    'subsequent_indent': indentation
}
result = '\n'.join([textwrap.fill(line, **params)
                    for line in input_text.splitlines()])

The str.splitlines() method is the easiest method to split lines by line separators. str.splitlines()方法是通过行分隔符拆分行的最简单方法。

Demo: 演示:

>>> import textwrap
>>> input_text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
>>> indentation = ';' + ' ' * 11
>>> result = textwrap.fill(
...     input_text, width=80,
...     initial_indent=indentation, subsequent_indent=indentation)
>>> print result
;           Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
;           eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
;           ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
;           aliquip ex ea commodo consequat. Duis aute irure dolor in
;           reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
;           pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
;           culpa qui officia deserunt mollit anim id est laborum.
>>>
>>> # produce a sample with newlines by inserting these around 170 characters
... 
>>> input_text = textwrap.fill(input_text, width=170)
>>> print input_text
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
>>> params = {
...     'width': 80,
...     'initial_indent': indentation,
...     'subsequent_indent': indentation
... }
>>> result = '\n'.join([textwrap.fill(line, **params)
...                     for line in input_text.splitlines()])
>>> print result
;           Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
;           eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
;           ad minim veniam, quis nostrud
;           exercitation ullamco laboris nisi ut aliquip ex ea commodo
;           consequat. Duis aute irure dolor in reprehenderit in voluptate velit
;           esse cillum dolore eu fugiat nulla
;           pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
;           culpa qui officia deserunt mollit anim id est laborum.

The width specified includes the indentation. 指定的宽度包括缩进。 Note that it'll use whitespace to wrap lines at whole words. 请注意,它将使用空格在整个单词处换行。 See the module documentation for more options to control how lines are wrapped. 请参阅模块文档以获取更多选项来控制换行方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM