python - 在 Python 2.7 中将长文本行分解为固定宽度的行

标签 python string text python-2.7 format

我如何在可能的空格处打断一个长字符串,如果没有则插入连字符,并且除了第一行之外的所有行都缩进?

因此,对于工作函数,breakup():

splitme = "Hello this is a long string and it may contain an extremelylongwordlikethis bye!"
breakup(bigline=splitme, width=20, indent=4)

会输出:

Hello this is a long
    string and it
    may contain an
    extremelylongwo-
    rdlikethis bye!

最佳答案

有一个标准的 Python 模块可以执行此操作:textwrap :

>>> import textwrap
>>> splitme = "Hello this is a long string and it may contain an extremelylongwordlikethis bye!"
>>> textwrap.wrap(splitme, width=10)
['Hello this', 'is a long', 'string and', 'it may', 'contain an', 'extremelyl', 'ongwordlik', 'ethis bye!']
>>> 

不过,它不会在断词时插入连字符。该模块有一个快捷函数 fill,它连接 wrap 生成的列表,因此它只是一个字符串。

>>> print textwrap.fill(splitme, width=10)
Hello this
is a long
string and
it may
contain an
extremelyl
ongwordlik
ethis bye!

要控制缩进,请使用关键字参数 initial_indentsubsequent_indent:

>>> print textwrap.fill(splitme, width=10, subsequent_indent=' ' * 4)
Hello this
    is a
    long
    string
    and it
    may co
    ntain
    an ext
    remely
    longwo
    rdlike
    this
    bye!
>>>

关于python - 在 Python 2.7 中将长文本行分解为固定宽度的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16319878/

相关文章:

iphone - NSString sizeWithFont : for multiple lines?

python - Django 1.9 URLField 删除必要的 http ://prefix

python - 如何解析可变长度分隔文件中的数据?

python - SQLAlchemy:获取具有最新日期的对象

java - 我不断收到字符串越界错误,有人可以帮助修复我的代码吗?

java - 将字符串转换为日期(复杂时区)

java - Int 无法转换为二进制字符串

iphone - 处理 iPhone/iPad 上使用 CGPDFScanner 获得的 PDF 文本矩阵 (Tm) 值

python - Sympy - limit() 错误 : Result depends on the sign

python - python中的动态调度和继承