2012-04-01 4 views
0

私は最大80文字の長い行だけを印刷したいと思っていますが、文字列はsであり、それより短くて長くてもかまいません。だから私はに分割し、の単語を分割しないで分割したいと思う。長い文字列のPythonで単語を分割せずに(潜在的に)長い文字列を分割する良い方法はありますか?

例:同様に、私はwhileループで繰り返しs.find(" ")を使用することができ

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 

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

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

私は、次のようなこれを行うための方法を考案することができます

これらのどれも非常にエレガントなものではありません。私の質問は、よりクーラー的なこの? (たぶん、正規表現とか、そう。)

+0

このPythonスクリプトを試すことができます。 http://stackoverflow.com/questions/9894983/wrapping-a-text-file-so-that-each-line-contain-a-max-of-80-characters –

+0

私は古い記事を検索していたので、私が_包装_について話している間に_splitting_を探していたのではないかと推測しますが、それは似ています。 – deinonychusaur

+0

まあ、これは技術的にはラッピングと呼ばれています。 –

答えて

13

は、そのためのモジュールがあります:textwrap

たとえば、あなたが

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

または

print textwrap.fill(s, 80) 
2
import re 
re.findall('.{1,80}(?:\W|$)', s) 
+0

これは基本的な単語ラッピングアルゴリズムと比較して悪い冗談です。 – delnan

+0

スピードの面ではありません。テキストラップに対してこれをベンチマークしただけで、約50倍速くなりました。 (速度がすべてではないことを知っている、興味深いのはすべてです) – bluepnume

+0

機能が不足している場合、速度は(ほぼ - あなたはまだ要件を変更しようとすることができます) – delnan

2
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)) 

を使用することができますout置く:

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

をあなたの質問は、私は数日前に尋ねた質問に似ています

import os, sys, 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!" 
limit = 83 
n = int(len(s)/limit) 
b = 0 
j= 0 
for i in range(n+2): 

    while 1: 
     if s[limit - j] not in [" ","\t"]: 
      j = j+1 
     else: 
      limit = limit - j 
      break 
    st = s[b:i*limit] 
    print st 
    b = i*limit 
関連する問題