Python の textwrap で文字列を折り返す(長さを超える単語を切らない方法)

Python の textwrap を使うと、文字列を折り返したときのリストを得られます。

import textwrap

text = "Hello. My   name  is pineapple. My only friend is peach."

chunks = textwrap.wrap(text, width=12)

print(chunks)
# ['Hello. My', 'name  is', 'pineapple.', 'My only', 'friend is', 'peach.']

分割された部分文字列はトリミングされています。ここで折り返す長さを短くするとパイナップルは分割されてしまいます。

import textwrap

text = "Hello. My   name  is pineapple. My only friend is peach."

chunks = textwrap.wrap(text, width=6)

print(chunks)
# ['Hello.', 'My', 'name', 'is pin', 'eapple', '. My', 'only', 'friend', 'is', 'peach.']

「長さを超えても単語は折り返さない」という制約があるときは break_long_words を False にします。

import textwrap

text = "Hello. My   name  is pineapple. My only friend is peach."

chunks = textwrap.wrap(text, width=6, break_long_words=False)

print(chunks)
# ['Hello.', 'My', 'name', 'is', 'pineapple.', 'My', 'only', 'friend', 'is', 'peach.']

パイナップルが切られずにすみました。