我想确保我只打印最多80个字符的长线,但我有一个字符串s
,它可以比这更短也可以更长。所以我想分割成行而不是分割任何单词。长字符串的有没有一种很好的方式分裂(可能)长的字符串,而不用在Python中分词?
例子:
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!"
我能想出这样做,例如方式:
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:]
:
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
同样我可以在一段时间循环使用s.find(" ")
反复
这些都不是非常优雅,所以我的问题是如果有更酷的pythonic方式做这个? (也许用正则表达式左右。)
你的问题看起来类似问题,我问前几天。 http://stackoverflow.com/questions/9894983/wrapping-a-text-file-so-that-each-line-contain-a-maximum-of-80-characters – 2012-04-01 20:53:09
我错过了那个寻找旧帖子的人,因为我在_wrapping_上讨论时寻找_splitting_,但是他们是相似的。 – deinonychusaur 2012-04-01 21:05:48
好吧,从技术上讲这叫做包装。 – 2012-04-01 21:10:26