かぴぶろぐ

またかぴったかと思った・・・(´A`;)

Python ○文字ごとに改行する

カテゴリ[ Python ]

2個前の記事と関連するけど、○文字ごとにテキストに改行したい時

def split_text(s, multiple):
    result = u""
   
    s = s.decode("utf8")
   
    for i in range(len(s)):
        if i > 0 and i % int(multiple) == 0:
            result += u"<br />" + s[i]
        else:
            result += s[i]
    return result.encode('utf8')

コード汚いけど(>_<)
ていうかこういうのやってくれるライブラリありそうだけど。

追記: textwrap

「textwrapがあるよ」というコメントいただきました。

で、サンプル書いてみました。

def split_text(s, multiple):
    import textwrap
    result=u""
    s = s.decode("utf8")
   
    result = textwrap.fill(s,  width=int(multiple))

    return result.encode('utf8')

実際変換部分は一行っすね。(^_^)

 

http://kapi.jp/kapi_blog/230

2009年05月14日

関連カテゴリ Python

この記事のコメント

textwrap [ methane ]

標準ライブラリの textwrap がそれです。

この記事にコメントする