Wrap and Truncate a String with textwrap in Python

Modified: | Tags: Python, String

In Python, to wrap or truncate a string to a specific width, use the textwrap module from the standard library.

For writing long strings in the code across multiple lines, refer to the following article.

The pprint module is useful for formatting lists and dictionaries.

All sample code in this article assumes that the textwrap module has been imported. As it is included in the standard library, no additional installation is required.

import textwrap

Wrap a string: textwrap.wrap(), textwrap.fill()

The textwrap.wrap() function splits a string into a list of segments, each fitting within the specified width.

Specify the target string as the first argument, and the number of characters as the second argument (width). By default, width is set to 70.

s = "Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages"

s_wrap_list = textwrap.wrap(s, 40)
print(s_wrap_list)
# ['Python can be easy to pick up whether', "you're a first time programmer or you're", 'experienced with other languages']

Using '\n'.join(list), a list is concatenated into a single string, with each element separated by the newline character \n.

print('\n'.join(s_wrap_list))
# Python can be easy to pick up whether
# you're a first time programmer or you're
# experienced with other languages

The textwrap.fill() function returns a string with line breaks instead of a list. It is equivalent to '\n'.join(textwrap.wrap(text, ...)).

If you only need a fixed-width string and not a list, textwrap.fill() is more convenient.

print(textwrap.fill(s, 40))
# Python can be easy to pick up whether
# you're a first time programmer or you're
# experienced with other languages

Both the textwrap.wrap() and textwrap.fill() functions accept the same keyword arguments.

The max_lines argument sets a limit on the number of lines, causing any additional lines to be omitted.

print(textwrap.wrap(s, 40, max_lines=2))
# ['Python can be easy to pick up whether', "you're a first time programmer or [...]"]

print(textwrap.fill(s, 40, max_lines=2))
# Python can be easy to pick up whether
# you're a first time programmer or [...]

By default, when truncation occurs, ' [...]' is appended to the end of the last line. You can replace this with any desired string by using the placeholder argument.

print(textwrap.fill(s, 40, max_lines=2, placeholder=' ~'))
# Python can be easy to pick up whether
# you're a first time programmer or ~

Additionally, the initial_indent argument allows you to specify a string to be added at the start of the first line, which is particularly useful for indenting the start of a paragraph.

print(textwrap.fill(s, 40, max_lines=2, placeholder=' ~', initial_indent='  '))
#   Python can be easy to pick up whether
# you're a first time programmer or ~

Truncate a string: textwrap.shorten()

The textwrap.shorten() function truncates a string to fit within the given width.

The placeholder is ' [...]', by default, and can be set with the placeholder argument. It is also included within the character count.

s = 'Python is powerful'

print(textwrap.shorten(s, 12))
# Python [...]

print(textwrap.shorten(s, 12, placeholder=' ~'))
# Python is ~

Use textwrap.TextWrapper instances

If you need to repeatedly use textwrap.wrap() or textwrap.fill() with consistent settings, it is efficient to create a textwrap.TextWrapper instance.

By creating an instance with arguments like width and max_lines in the constructor, you can efficiently execute the wrap() or fill() methods repeatedly with these consistent settings.

tw = textwrap.TextWrapper(width=30, max_lines=3, placeholder=' ~', initial_indent='  ')

s = "Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages"

print(tw.wrap(s))
# ['  Python can be easy to pick', "up whether you're a first time", "programmer or you're ~"]

print(tw.fill(s))
#   Python can be easy to pick
# up whether you're a first time
# programmer or you're ~

Additionally, it is possible to change the settings after the instance has been created by modifying its attributes.

tw.placeholder = ' ...'
tw.initial_indent = ''

print(tw.fill(s))
# Python can be easy to pick up
# whether you're a first time
# programmer or you're ...

Related Categories

Related Articles