Search code examples
pythonword-wrap

Python textwrap don't split words


I have a phrase and i want to wrap it i a width of 13 using:

self.wrapped_phrase = "\n ".join(textwrap.wrap(phrase, width=13))

that was working perfectly until one of the word is higher than 13, in this case it's just splitting the word. Is there a way to don't split the word and just leave it like that?


Solution

  • As the docs say break_long_words defaults to true and setting it to false should do the trick.

    break_long_words: (default: True) If true, then words longer than width will be broken in order to ensure that no lines are longer than width. If it is false, long words will not be broken, and some lines may be longer than width. (Long words will be put on a line by themselves, in order to minimize the amount by which width is exceeded.)

    Link to the docs: https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper

    Happy Coding, T