Coverage for src/extratools_core/clitools.py: 0%
18 statements
« prev ^ index » next coverage.py v7.8.1, created at 2025-05-27 07:45 -0700
« prev ^ index » next coverage.py v7.8.1, created at 2025-05-27 07:45 -0700
1from collections.abc import Iterable
2from io import StringIO
3from itertools import zip_longest
5from wcwidth import wcswidth
8def alignment_to_str[T](
9 *seqs: Iterable[T | None],
10 default: str = "",
11 separator: str = " | ",
12) -> str:
13 """
14 Example:
15 ``` python
16 In [1]: from extratools_core.cli import alignment_to_str
18 In [2]: print(alignment_to_str(["吃饭", "喝水", "看电视"], ["Ada", "Bob", "Chad"]))
19 '吃饭' | '喝水' | '看电视'
20 'Ada' | 'Bob' | 'Chad'
21 ```
22 """
24 strs: list[StringIO] = []
26 for i, col in enumerate(zip_longest(*seqs, fillvalue=default)):
27 if i == 0:
28 strs = [StringIO() for _ in col]
29 else:
30 for s in strs:
31 s.write(separator)
33 vals: list[str] = [
34 default if v is None else repr(v)
35 for v in col
36 ]
37 max_width: int = max(
38 wcswidth(val)
39 for val in vals
40 )
41 pads: list[str] = [
42 (max_width - wcswidth(val)) * ' '
43 for val in vals
44 ]
46 for s, pad, val in zip(strs, pads, vals, strict=True):
47 s.write(val)
48 s.write(pad)
50 return '\n'.join([s.getvalue() for s in strs])