有没有一种很好的方法来拆分(可能)长字符串而不在 Python 中拆分单词? [英] Is there a nice way splitting a (potentially) long string without splitting in words in Python?

查看:15
本文介绍了有没有一种很好的方法来拆分(可能)长字符串而不在 Python 中拆分单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make sure that I only print maximum 80 character long lines, but I have a string s that can be both shorter and longer than that. So I want to split it into lines without splitting any words.

长字符串示例:

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!"

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

I can devise ways of doing this such as:

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(" "):

Equally I could use s.find(" ") iteratively in a while-loop:

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方式来做到这一点?(也许使用正则表达式左右.)

None of these are very elegant, so my question is if there's a cooler pythonic way of doing this? (Maybe with regex or so.)

推荐答案

有一个模块:文本换行

例如,您可以使用

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

print textwrap.fill(s, 80)

这篇关于有没有一种很好的方法来拆分(可能)长字符串而不在 Python 中拆分单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆