A tool for wrapping and filling text.
Project description
TxTWrap🔡
A tool for wrapping and filling text.🔨
Package version: 3.0.1
Python requires version: >=3.0.0
Python stub file requires version: >=3.5.0
LOREM_IPSUM_WORDSLOREM_IPSUM_SENTENCESLOREM_IPSUM_PARAGRAPHSSEPARATOR_WHITESPACESEPARATOR_ESCAPETextWrapper(🛠️ Fixed)sanitize(🛠️ Fixed)wrap(🛠️ Fixed)align(🛠️ Fixed)fillstr(🛠️ Fixed)shorten(🛠️ Fixed)
Documents📄
This module is inspired by the textwrap module, which provides
several useful functions, along with the TextWrapper, class that handles all available functions.
The difference between txtwrap and
textwrap is that this module is designed not only for wrapping and
filling monospace fonts but also for other font types, such as Arial, Times New Roman, and more.
Constants
File: txtwrap.constants
Lorem ipsum
LOREM_IPSUM_WORDS
LOREM_IPSUM_SENTENCES
LOREM_IPSUM_PARAGRAPHS
A Lorem Ipsum collection of words, sentences, and paragraphs that can be used as examples.
LOREM_IPSUM_WORDScontains a short sentence.LOREM_IPSUM_SENTENCEScontains a slightly longer paragraph.LOREM_IPSUM_PARAGRAPHScontains several longer paragraphs.
Separators
SEPARATOR_WHITESPACE
SEPARATOR_ESCAPE
A collection of separators that can be used to separate text.
SEPARATOR_WHITESPACEcontains whitespace characters.SEPARATOR_ESCAPEcontains whitespace characters including'\0','\a', and'\b'.
To use this, assign this constant to the separator parameter.
TextWrapper
File: txtwrap.wrapper
class TextWrapper:
def __init__(
self,
width: Union[int, float] = 70,
line_padding: Union[int, float] = 0,
mode: Literal['mono', 'word'] = 'word',
alignment: Literal['left', 'center', 'right', 'fill', 'fill-left', 'fill-center', 'fill-right'] = 'left',
placeholder: str = '...',
fillchar: str = ' ',
separator: Optional[Union[str, Iterable[str]]] = None,
max_lines: Optional[int] = None,
preserve_empty_lines: bool = True,
minimum_width: bool = True,
drop_separator: bool = False,
justify_last_line: bool = False,
break_on_hyphens: bool = True,
sizefunc: Optional[Callable[[str], Union[Tuple[Union[int, float], Union[int, float]], int, float]]] = None
) -> None
A class that handles all functions available in this module. Each keyword argument corresponds to its attribute. For example:
wrapper = TextWrapper(width=100)
is equivalent to:
wrapper = TextWrapper()
wrapper.width = 100
You can reuse TextWrapper multiple times or modify its options by assigning new values to its
attributes. However, it is recommended not to reuse TextWrapper too frequently inside a specific loop,
as each attribute has type checking, which may reduce performance.
Attributes of TextWrapper:
width
(Default: 70) The maximum line length for wrapped text.
line_padding
(Default: 0) The spacing between wrapped lines.
mode
(Default: 'word') The wrapping mode. Available options:
'mono'make text wraps character by character.'word'make text wraps word by word.
alignment
(Default: 'left') The alignment of the wrapped text. Available options:
'left': Aligns text to the start of the line.'center': Centers text within the line.'right': Aligns text to the end of the line.'fill'or'fill-left': Justifies text across the width but aligns single-word lines or the last line (ifjustify_last_lineisFalse) to the left.'fill-center'and'fill-right'work the same way as'fill-left', aligning text according to their respective names.
placeholder
(Default: '...') The ellipsis used for truncating long lines.
fillchar
(Default: ' ') The character used for padding.
separator
(Default: None) The character used to separate words.
None: Uses whitespace as the separator.str: Uses the specified character.Iterable[str]: Uses multiple specified characters.
max_lines
(Default: None) The maximum number of wrapped lines.
None: No limit on the number of wrapped lines.int: Limits the number of wrapped lines to the specified value. (Ensure thatwidthis not smaller than the length ofplaceholder).
preserve_empty_lines
(Default: True) Retains empty lines in the wrapped text.
minimum_width
(Default: True) Uses the minimum required line width. Some wrapped lines may be shorter than the specified width, so
enabling this attribute removes unnecessary empty space.
drop_separator
(Default: False) Removes excess separators from between words one at a time.
justify_last_line
(Default: False) Determines whether the last line should also be justified
(applies only to fill-... alignments).
break_on_hyphens
(Default: True) Breaks words at hyphens (-). Example 'self-organization' becomes 'self-' and 'organization'.
sizefunc
(Default: None) A function used to calculate the width and height or only the width of each string.
If the function calculates both width and height, it must return a tuple containing two values:
- The width and height of the string.
- Both values must be of type
intorfloat.
If the function calculates only the width, it must return a single value of type int or float.
Methods of TextWrapper:
Note: All methods can be called outside the
TextWrapperlike external functions.
For example:
>>> txtwrap.TextWrapper(20, placeholder='[...]').shorten("Hello World!")
is equivalent to:
>>> txtwrap.shorten("Hello World!", 20, placeholder='[...]')
copy
Creates and returns a copy of the TextWrapper object. (External function using copy.copy)
sanitize(text)
Removes excessive characters from separator and replaces them with the fillchar
character. (It doesn't matter whether drop_separator is False or True)
For example:
>>> txtwrap.sanitize("\tHello \nWorld!\r ")
'Hello World!'
wrap(text, return_details=False)
Returns a list of wrapped text strings. If return_details=True, returns a dictionary containing:
'wrapped': A list of wrapped text fragments.'start_lines': A list of indices marking the start of line.'end_lines': A list of indices marking the end of line.
For example:
>>> txtwrap.wrap(txtwrap.LOREM_IPSUM_WORDS, width=20)
['Lorem ipsum odor', 'amet, consectetuer', 'adipiscing elit.']
>>> wrapped_info = txtwrap.wrap(txtwrap.LOREM_IPSUM_WORDS, width=20, return_details=True)
>>> start_lines = wrapped_info['start_lines']
>>> end_lines = wrapped_info['end_lines']
>>> wrapped_info
{'wrapped': ['Lorem ipsum odor', 'amet, consectetuer', 'adipiscing elit.'], 'start_lines': [1], 'end_lines': [3]}
>>> wrapped_info['wrapped'][start_lines[0] - 1]
'Lorem ipsum odor'
>>> wrapped_info['wrapped'][end_lines[0] - 1]
'adipiscing elit.'
align(text, return_details=False)
Returns a list of tuples, where each tuple contains (xPosition, yPosition, text), representing the wrapped text along
with its coordinates.
Note:
sizefuncmust return both width and height.
If return_details=True, returns a dictionary containing:
'aligned': A list of wrapped text with coordinate data.'wrapped': A list of wrapped text fragments.'start_lines': A list of indices marking the start of line.'end_lines': A list of indices marking the end of line.'size': A calculated text size.
For example:
>>> txtwrap.align(txtwrap.LOREM_IPSUM_WORDS, width=20)
[(0, 0, 'Lorem ipsum odor'), (0, 1, 'amet, consectetuer'), (0, 2, 'adipiscing elit.')]
>>> aligned_info = txtwrap.align(txtwrap.LOREM_IPSUM_WORDS, width=20, return_details=True)
>>> start_lines = aligned_info['start_lines']
>>> end_lines = aligned_info['end_lines']
>>> aligned_info
{'aligned': [(0, 0, 'Lorem ipsum odor'), (0, 1, 'amet, consectetuer'), (0, 2, 'adipiscing elit.')], 'wrapped': [
'Lorem ipsum odor', 'amet, consectetuer', 'adipiscing elit.'], 'start_lines': [1], 'end_lines': [3], 'size': (18, 3)}
>>> aligned_info['wrapped'][start_lines[0] - 1]
'Lorem ipsum odor'
>>> aligned_info['wrapped'][end_lines[0] - 1]
'adipiscing elit.'
fillstr(text)
Returns a string with wrapped text formatted for monospace fonts.
Note:
width,line_padding, and the output ofsizefunc(size or just length) must returnint, notfloat!
For example:
>>> s = txtwrap.fillstr(txtwrap.LOREM_IPSUM_WORDS, width=20)
>>> s
'Lorem ipsum odor \namet, consectetuer\nadipiscing elit. '
>>> print(s)
Lorem ipsum odor
amet, consectetuer
adipiscing elit.
shorten(text)
Returns a truncated string if its length exceeds width, appending placeholder at the end
if truncated.
For example:
>>> txtwrap.shorten(txtwrap.LOREM_IPSUM_WORDS, width=20)
'Lorem ipsum odor...'
Another examples❓
Render a wrap text in PyGame🎮
from typing import Literal, Optional
from txtwrap import align, LOREM_IPSUM_PARAGRAPHS
import pygame
def render_wrap(
font: pygame.Font,
text: str,
width: int,
antialias: bool,
color: pygame.Color,
background: Optional[pygame.Color] = None,
line_padding: int = 0,
wrap_mode: Literal['word', 'mono'] = 'word',
alignment: Literal['left', 'center', 'right', 'fill', 'fill-left', 'fill-center', 'fill-right'] = 'left',
placeholder: str = '...',
max_lines: Optional[int] = None,
preserve_empty_lines: bool = True,
minimum_width: bool = True,
drop_separator: bool = False,
justify_last_line: bool = False,
break_on_hyphens: bool = True
) -> pygame.Surface:
align_info = align(
text=text,
width=width,
line_padding=line_padding,
mode=wrap_mode,
alignment=alignment,
placeholder=placeholder,
max_lines=max_lines,
preserve_empty_lines=preserve_empty_lines,
minimum_width=minimum_width,
drop_separator=drop_separator,
justify_last_line=justify_last_line,
break_on_hyphens=break_on_hyphens,
return_details=True,
sizefunc=font.size
)
surface = pygame.Surface(align_info['size'], pygame.SRCALPHA)
if background is not None:
surface.fill(background)
for x, y, text in align_info['aligned']:
surface.blit(font.render(text, antialias, color), (x, y))
return surface
# Example usage:
pygame.init()
pygame.display.set_caption("Lorem Ipsum")
running = True
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
surface = render_wrap(
font=pygame.font.SysFont('Arial', 18),
text=LOREM_IPSUM_PARAGRAPHS,
width=width,
antialias=True,
color='#ffffff',
background='#303030',
alignment='fill'
)
width_surface, height_surface = surface.get_size()
pos = ((width - width_surface) / 2, (height - height_surface) / 2)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill('#000000')
screen.blit(surface, pos)
pygame.display.flip()
clock.tick(60)
Short a long text🔤
from txtwrap import shorten, LOREM_IPSUM_SENTENCES
print(shorten(LOREM_IPSUM_SENTENCES, width=50, placeholder='…'))
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file txtwrap-3.0.1.tar.gz.
File metadata
- Download URL: txtwrap-3.0.1.tar.gz
- Upload date:
- Size: 17.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
24bc5e3aedd50551334216db5c32576e651d962f6db0ad69d044be9fa40e6821
|
|
| MD5 |
3123424b6b3866f4ac2f6c6a922a05a3
|
|
| BLAKE2b-256 |
4b7baefb183d330c1d1839af00daac75f1d27b49d8534ba70b4270e94ad7eb02
|