MCPcopy Index your code
hub / github.com/rspeer/python-ftfy / monospaced_width

Function monospaced_width

ftfy/formatting.py:37–76  ·  view source on GitHub ↗

r""" Return the number of character cells that this string is likely to occupy when displayed in a monospaced, modern, Unicode-aware terminal emulator. We refer to this as the "display width" of the string. This can be useful for formatting text that may contain non-spacing char

(text: str)

Source from the content-addressed store, hash-verified

35
36
37def monospaced_width(text: str) -> int:
38 r"""
39 Return the number of character cells that this string is likely to occupy
40 when displayed in a monospaced, modern, Unicode-aware terminal emulator.
41 We refer to this as the "display width" of the string.
42
43 This can be useful for formatting text that may contain non-spacing
44 characters, or CJK characters that take up two character cells.
45
46 Returns -1 if the string contains a non-printable or control character.
47
48 >>> monospaced_width('ちゃぶ台返し')
49 12
50 >>> len('ちゃぶ台返し')
51 6
52 >>> monospaced_width('owl\N{SOFT HYPHEN}flavored')
53 11
54 >>> monospaced_width('example\x80')
55 -1
56
57 A more complex example: The Korean word 'ibnida' can be written with 3
58 pre-composed characters or 7 jamo. Either way, it *looks* the same and
59 takes up 6 character cells.
60
61 >>> monospaced_width('입니다')
62 6
63 >>> monospaced_width('\u110b\u1175\u11b8\u1102\u1175\u1103\u1161')
64 6
65
66 The word "blue" with terminal escapes to make it blue still takes up only
67 4 characters, when shown as intended.
68 >>> monospaced_width('\x1b[34mblue\x1b[m')
69 4
70 """
71 # NFC-normalize the text first, so that we don't need special cases for
72 # Hangul jamo.
73 #
74 # Remove terminal escapes before calculating width, because if they are
75 # displayed as intended, they will have zero width.
76 return int(wcswidth(remove_terminal_escapes(normalize("NFC", text))))
77
78
79def display_ljust(text: str, width: int, fillchar: str = " ") -> str:

Callers 3

display_ljustFunction · 0.85
display_rjustFunction · 0.85
display_centerFunction · 0.85

Calls 1

remove_terminal_escapesFunction · 0.90

Tested by

no test coverage detected