是否有一种很好的方法来分割(可能)长字符串而不在Python中分割单词?

dei*_*aur 0 python string split cpu-word word-wrap

我想确保我只打印最多80个字符的长行,但我有一个字符串s,可以更短,更长.所以我想把它分成几行而不分裂任何单词.

长字符串示例:

s = "This is a long string that is holding more than 80 characters and thus should be split into several lines. That is if everything is working properly and nicely and all that. No mishaps no typos. No bugs. But I want the code too look good too. That's the problem!"
Run Code Online (Sandbox Code Playgroud)

我可以设计出这样做的方法,例如:

words = s.split(" ")
line = ""
for w in words:
    if len(line) + len(w) <= 80:
        line += "%s " % w
    else:
        print line
        line ="%s " % w

print line
Run Code Online (Sandbox Code Playgroud)

同样,我可以s.find(" ")在while循环中迭代使用:

sub_str_left = 0
pos = 0
next_pos = s.find(" ", pos)
while next_pos > -1:
    if next_pos - sub_str_left > 80:
        print s[sub_str_left:pos-sub_str_left]
        sub_str_left = pos + 1

    pos = next_pos
    next_pos = s.find(" ", pos)

print s[sub_str_left:]
Run Code Online (Sandbox Code Playgroud)

这些都不是很优雅,所以我的问题是,如果有更冷静的pythonic方式吗?(也许是正则表达式.)

Ste*_*eef 14

有一个模块:textwrap

例如,你可以使用

print '\n'.join(textwrap.wrap(s, 80))
Run Code Online (Sandbox Code Playgroud)

要么

print textwrap.fill(s, 80)
Run Code Online (Sandbox Code Playgroud)


blu*_*ume 6

import re
re.findall('.{1,80}(?:\W|$)', s)
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 5

import re

s = "This is a long string that is holding more than 80 characters and thus should be split into several lines. That is if everything is working properly and nicely and all that. No misshaps no typos. No bugs. But I want the code too look good too. That's the problem!"

print '\n'.join(line.strip() for line in re.findall(r'.{1,80}(?:\s+|$)', s))
Run Code Online (Sandbox Code Playgroud)

输出:

This is a long string that is holding more than 80 characters and thus should be
split into several lines. That is if everything is working properly and nicely
and all that. No misshaps no typos. No bugs. But I want the code too look good
too. That's the problem!
Run Code Online (Sandbox Code Playgroud)