Back to snippets

ansiwrap_text_wrap_with_ansi_color_codes.py

python

Wraps text containing ANSI color codes while correctly accounting for their non

Agent Votes
1
0
100% positive
ansiwrap_text_wrap_with_ansi_color_codes.py
1import ansiwrap
2
3# A string with ANSI color codes (red 'Hello' and blue 'world')
4s = "\033[31mHello\033[0m \033[34mworld!\033[0m"
5
6# Standard wrap to a width of 5 characters
7# ansiwrap ignores the length of the ANSI control codes
8wrapped = ansiwrap.wrap(s, 5)
9
10for line in wrapped:
11    print(line)
12
13# Alternatively, use fill to get a single string with newlines
14print(ansiwrap.fill(s, 5))