text_helper.py
 1  # SPDX-FileCopyrightText: 2020 FoamyGuy for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  def wrap_nicely(string, max_chars):
 6      """ From: https://www.richa1.com/RichardAlbritton/circuitpython-word-wrap-for-label-text/
 7      A helper that will return the string with word-break wrapping.
 8      :param str string: The text to be wrapped.
 9      :param int max_chars: The maximum number of characters on a line before wrapping.
10      """
11      string = string.replace("\n", "").replace("\r", "")  # strip confusing newlines
12      words = string.split(" ")
13      the_lines = []
14      the_line = ""
15      for w in words:
16          if len(the_line + " " + w) <= max_chars:
17              the_line += " " + w
18          else:
19              the_lines.append(the_line)
20              the_line = w
21      if the_line:
22          the_lines.append(the_line)
23      the_lines[0] = the_lines[0][1:]
24      the_newline = ""
25      for w in the_lines:
26          the_newline += "\n" + w
27      return the_newline