python - 有没有一种很好的方法来拆分(可能)长的字符串而不用 Python 中的单词拆分?

我想确保我只打印最多 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!"

我可以想出一些方法来做到这一点,例如:

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

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

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:]

这些都不是很优雅,所以我的问题是是否有更酷的 pythonic 方式来做到这一点? (也许使用正则表达式。)

最佳答案

有一个模块:textwrap

例如,您可以使用

print '\n'.join(textwrap.wrap(s, 80))

print textwrap.fill(s, 80)

https://stackoverflow.com/questions/9968173/

相关文章:

vb.net - 如何拆分逗号分隔的字符串?

objective-c - 比较 objective-C 中的 2 个字符串

javascript - 如何更改 react js中的默认端口

r - 在 R 中转换日期格式

java - 为什么我在 Java 中对 char 和 int 进行比较不起作用?

python - 如何将 __repr__ 与多个参数一起使用?

c - 如何在 yocto 中编译一个基本的 c 文件

python - 如何获取和使用 Dropbox API 的刷新 token (Python 3.x

php - 无法移 Action 曲家

macos - Applescript 制作新文件夹