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

Function display_center

ftfy/formatting.py:142–166  ·  view source on GitHub ↗

Return `text` centered in a Unicode string whose display width, in a monospaced terminal, should be at least `width` character cells. The rest of the string will be padded with `fillchar`, which must be a width-1 character. >>> lines = ['Table flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し']

(text: str, width: int, fillchar: str = " ")

Source from the content-addressed store, hash-verified

140
141
142def display_center(text: str, width: int, fillchar: str = " ") -> str:
143 """
144 Return `text` centered in a Unicode string whose display width, in a
145 monospaced terminal, should be at least `width` character cells. The rest
146 of the string will be padded with `fillchar`, which must be a width-1
147 character.
148
149 >>> lines = ['Table flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し']
150 >>> for line in lines:
151 ... print(display_center(line, 20, '▒'))
152 ▒▒▒▒▒Table flip▒▒▒▒▒
153 ▒▒▒(╯°□°)╯︵ ┻━┻▒▒▒▒
154 ▒▒▒▒ちゃぶ台返し▒▒▒▒
155 """
156 if character_width(fillchar) != 1:
157 raise ValueError("The padding character must have display width 1")
158
159 text_width = monospaced_width(text)
160 if text_width == -1:
161 return text
162
163 padding = max(0, width - text_width)
164 left_padding = padding // 2
165 right_padding = padding - left_padding
166 return fillchar * left_padding + text + fillchar * right_padding

Callers

nothing calls this directly

Calls 2

character_widthFunction · 0.85
monospaced_widthFunction · 0.85

Tested by

no test coverage detected