私は最大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!"
私は、次のようなこれを行うための方法を考案することができます
これらのどれも非常にエレガントなものではありません。私の質問は、よりクーラー的なこの? (たぶん、正規表現とか、そう。)
このPythonスクリプトを試すことができます。 http://stackoverflow.com/questions/9894983/wrapping-a-text-file-so-that-each-line-contain-a-max-of-80-characters –
私は古い記事を検索していたので、私が_包装_について話している間に_splitting_を探していたのではないかと推測しますが、それは似ています。 – deinonychusaur
まあ、これは技術的にはラッピングと呼ばれています。 –