Skip to content

fmts

fmts ⚓︎

String utils

Classes⚓︎

fmts.HTML ⚓︎

HTML formatting utils staticmethod container

Functions⚓︎
fmts.HTML.html_tag(tag_str: str, string: str = '') -> str staticmethod ⚓︎

Return an HTML tag with a string as the innerHTML

Source code in libs/fmts/fmts/__init__.py
1415
1416
1417
1418
@staticmethod
def html_tag(tag_str: str, string: str = "") -> str:
    """Return an HTML tag with a string as the innerHTML"""
    return f"<{tag_str}>{string}</{tag_str}>"
fmts.HTML.table(string: str) -> str staticmethod ⚓︎

Return an string surrounded with 'table-HTML' tags

Parameters:

Name Type Description Default
string str

Input string

required

Returns:

Type Description
str

Formatted string

Examples:

>>> HTML.table("string")
'<table>string</table>'
Source code in libs/fmts/fmts/__init__.py
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
@staticmethod
def table(string: str) -> str:
    """Return an string surrounded with 'table-HTML' tags

    Args:
        string: Input string

    Returns:
        Formatted string

    Examples:
        >>> HTML.table("string")
        '<table>string</table>'

    """
    return HTML.html_tag("table", string)
fmts.HTML.tablebody(string: str) -> str staticmethod ⚓︎

Return an string surrounded with 'tbody-HTML' tags

Parameters:

Name Type Description Default
string str

Input string

required

Returns:

Type Description
str

Formatted string

Examples:

>>> HTML.tablebody("string")
'<tbody>string</tbody>'
Source code in libs/fmts/fmts/__init__.py
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
@staticmethod
def tablebody(string: str) -> str:
    """Return an string surrounded with 'tbody-HTML' tags

    Args:
        string: Input string

    Returns:
        Formatted string

    Examples:
        >>> HTML.tablebody("string")
        '<tbody>string</tbody>'

    """
    return HTML.html_tag("tbody", string)
fmts.HTML.tablehead(string: str) -> str staticmethod ⚓︎

Return an string surrounded with 'thead-HTML' tags

Parameters:

Name Type Description Default
string str

Input string

required

Returns:

Type Description
str

Formatted string

Examples:

>>> HTML.tablehead("string")
'<thead>string</thead>'
Source code in libs/fmts/fmts/__init__.py
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
@staticmethod
def tablehead(string: str) -> str:
    """Return an string surrounded with 'thead-HTML' tags

    Args:
        string: Input string

    Returns:
        Formatted string

    Examples:
        >>> HTML.tablehead("string")
        '<thead>string</thead>'

    """
    return HTML.html_tag("thead", string)
fmts.HTML.tbody(string: str) -> str staticmethod ⚓︎

Return an string surrounded with 'tbody-HTML' tags

Parameters:

Name Type Description Default
string str

Input string

required

Returns:

Type Description
str

Formatted string

Examples:

>>> HTML.tbody("string")
'<tbody>string</tbody>'
Source code in libs/fmts/fmts/__init__.py
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
@staticmethod
def tbody(string: str) -> str:
    """Return an string surrounded with 'tbody-HTML' tags

    Args:
        string: Input string

    Returns:
        Formatted string

    Examples:
        >>> HTML.tbody("string")
        '<tbody>string</tbody>'

    """
    return HTML.html_tag("tbody", string)
fmts.HTML.td(string: str) -> str staticmethod ⚓︎

Return an string surrounded with 'td-HTML' tags

Parameters:

Name Type Description Default
string str

Input string

required

Returns:

Type Description
str

Formatted string

Examples:

>>> HTML.td("string")
'<td>string</td>'
Source code in libs/fmts/fmts/__init__.py
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
@staticmethod
def td(string: str) -> str:
    """Return an string surrounded with 'td-HTML' tags

    Args:
        string: Input string

    Returns:
        Formatted string

    Examples:
        >>> HTML.td("string")
        '<td>string</td>'

    """
    return HTML.html_tag("td", string)
fmts.HTML.th(string: str) -> str staticmethod ⚓︎

Return an string surrounded with 'th-HTML' tags

Parameters:

Name Type Description Default
string str

Input string

required

Returns:

Type Description
str

Formatted string

Examples:

>>> HTML.th("string")
'<th>string</th>'
Source code in libs/fmts/fmts/__init__.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
@staticmethod
def th(string: str) -> str:
    """Return an string surrounded with 'th-HTML' tags

    Args:
        string: Input string

    Returns:
        Formatted string

    Examples:
        >>> HTML.th("string")
        '<th>string</th>'

    """
    return HTML.html_tag("th", string)
fmts.HTML.thead(string: str) -> str staticmethod ⚓︎

Return an string surrounded with 'thead-HTML' tags

Parameters:

Name Type Description Default
string str

Input string

required

Returns:

Type Description
str

Formatted string

Examples:

>>> HTML.thead("string")
'<thead>string</thead>'
Source code in libs/fmts/fmts/__init__.py
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
@staticmethod
def thead(string: str) -> str:
    """Return an string surrounded with 'thead-HTML' tags

    Args:
        string: Input string

    Returns:
        Formatted string

    Examples:
        >>> HTML.thead("string")
        '<thead>string</thead>'

    """
    return HTML.html_tag("thead", string)
fmts.HTML.tr(string: str) -> str staticmethod ⚓︎

Return an string surrounded with 'tr-HTML' tags

Parameters:

Name Type Description Default
string str

Input string

required

Returns:

Type Description
str

Formatted string

Examples:

>>> HTML.tr("string")
'<tr>string</tr>'
Source code in libs/fmts/fmts/__init__.py
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
@staticmethod
def tr(string: str) -> str:
    """Return an string surrounded with 'tr-HTML' tags

    Args:
        string: Input string

    Returns:
        Formatted string

    Examples:
        >>> HTML.tr("string")
        '<tr>string</tr>'

    """
    return HTML.html_tag("tr", string)

fmts.pstr ⚓︎

Bases: str

Pretty-string subclass

Functions⚓︎
fmts.pstr.__new__(content: str) -> 'pstr' ⚓︎

Create and return new pstr from a str

Source code in libs/fmts/fmts/__init__.py
1296
1297
1298
1299
1300
def __new__(cls, content: str) -> "pstr":
    """Create and return new pstr from a str"""
    if "\n" in content and (content[0] == "\n" or content[-1] == "\n"):
        return str.__new__(cls, content.strip("\n"))
    return str.__new__(cls, content)

Functions⚓︎

fmts.anystr(fn: Callable[[str], _R]) -> Callable[[AnyStr], _R] ⚓︎

Convert a given function to accept any string type

Parameters:

Name Type Description Default
fn Callable[[str], _R]

function to convert

required

Returns:

Type Description
Callable[[AnyStr], _R]

Callable[[AnyStr], R]: function that accepts one arg that is a string

Examples:

>>> def _is_upper(string: str) -> bool:
...     return string == string.upper()
>>> is_upper = anystr(_is_upper)
>>> is_upper('hello')
False
>>> is_upper('HELLO')
True
>>> is_upper(b'hello')
False
>>> is_upper(b'HELLO')
True
Source code in libs/fmts/fmts/__init__.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def anystr(fn: Callable[[str], _R]) -> Callable[[AnyStr], _R]:
    """Convert a given function to accept any string type

    Args:
        fn: function to convert

    Returns:
        Callable[[AnyStr], R]: function that accepts one arg that is a string

    Examples:
        >>> def _is_upper(string: str) -> bool:
        ...     return string == string.upper()
        >>> is_upper = anystr(_is_upper)
        >>> is_upper('hello')
        False
        >>> is_upper('HELLO')
        True
        >>> is_upper(b'hello')
        False
        >>> is_upper(b'HELLO')
        True

    """

    def _anystr(string: AnyStr) -> _R:
        if isinstance(string, bytes):
            return fn(string.decode())
        return fn(string)

    _anystr.__name__ = fn.__name__
    _anystr.__doc__ = fn.__doc__
    if hasattr(fn, "__module__"):
        _anystr.__module__ = fn.__module__

    return _anystr

fmts.anystr2anystr(fn: Callable[[str], str]) -> Callable[[AnyStr], AnyStr] ⚓︎

Convert a str-to-str function to allow for AnyStr

Parameters:

Name Type Description Default
fn Callable[[str], str]

function to convert

required

Returns:

Type Description
Callable[[AnyStr], AnyStr]

Callable[[AnyStr], AnyStr]: function that accepts any string type

Source code in libs/fmts/fmts/__init__.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def anystr2anystr(fn: Callable[[str], str]) -> Callable[[AnyStr], AnyStr]:
    """Convert a str-to-str function to allow for `AnyStr`

    Args:
        fn: function to convert

    Returns:
        Callable[[AnyStr], AnyStr]: function that accepts any string type

    """

    def _anystr2anystr(string: AnyStr) -> AnyStr:
        if isinstance(string, bytes):
            return fn(string.decode()).encode()
        return fn(string)

    _anystr2anystr.__name__ = fn.__name__
    _anystr2anystr.__doc__ = fn.__doc__
    if hasattr(fn, "__module__"):
        _anystr2anystr.__module__ = fn.__module__
    return _anystr2anystr

fmts.b64_html_gif(b64_string: str) -> str ⚓︎

Return a HTML base64 gif image tag

Parameters:

Name Type Description Default
b64_string str

Base64 gif image string

required

Returns:

Name Type Description
str str

base64 html image tag

Examples:

>>> b64_html_gif("BASE64_STRING")
'<img src="data:image/gif;base64,BASE64_STRING">'
Source code in libs/fmts/fmts/__init__.py
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
def b64_html_gif(b64_string: str) -> str:
    """Return a HTML base64 gif image tag

    Args:
        b64_string (str): Base64 gif image string

    Returns:
        str: base64 html image tag

    Examples:
        >>> b64_html_gif("BASE64_STRING")
        '<img src="data:image/gif;base64,BASE64_STRING">'

    """
    return b64_html_img(b64_string, "gif")

fmts.b64_html_img(b64_string: Union[str, bytes], img_format: str) -> str ⚓︎

Return an img tag given a base64-jpeg-image-string

Source code in libs/fmts/fmts/__init__.py
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
def b64_html_img(b64_string: Union[str, bytes], img_format: str) -> str:
    """Return an img tag given a base64-jpeg-image-string"""
    try:
        if isinstance(b64_string, bytes):
            b64_string = b64_string.decode("utf-8")
    except UnicodeDecodeError as ude:
        raise ValueError(
            "bytes given instead of string;\n"
            f"tried to decode but got UnicodeDecodeError:\n{str(ude)}"
        ) from ude
    return f'<img src="data:image/{img_format};base64,{b64_string}">'

fmts.b64_html_jpg(b64_string: str) -> str ⚓︎

Return a HTML base64 jpg image tag

Parameters:

Name Type Description Default
b64_string str

Base64 jpg image string

required

Returns:

Name Type Description
str str

base64 html jpg image tag

Examples:

>>> b64_html_jpg("BASE64_STRING")
'<img src="data:image/jpg;base64,BASE64_STRING">'
Source code in libs/fmts/fmts/__init__.py
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
def b64_html_jpg(b64_string: str) -> str:
    """Return a HTML base64 jpg image tag

    Args:
        b64_string (str): Base64 jpg image string

    Returns:
        str: base64 html jpg image tag

    Examples:
        >>> b64_html_jpg("BASE64_STRING")
        '<img src="data:image/jpg;base64,BASE64_STRING">'

    """
    return b64_html_img(b64_string, "jpg")

fmts.b64_html_png(b64_string: str) -> str ⚓︎

Return a HTML base64 png image tag

Parameters:

Name Type Description Default
b64_string str

Base64 image string

required

Returns:

Name Type Description
str str

base64 html image tag

Examples:

>>> b64_html_png("BASE64_STRING")
'<img src="data:image/png;base64,BASE64_STRING">'
Source code in libs/fmts/fmts/__init__.py
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
def b64_html_png(b64_string: str) -> str:
    """Return a HTML base64 png image tag

    Args:
        b64_string (str): Base64 image string

    Returns:
        str: base64 html image tag

    Examples:
        >>> b64_html_png("BASE64_STRING")
        '<img src="data:image/png;base64,BASE64_STRING">'

    """
    return b64_html_img(b64_string, "png")

fmts.base64_jpg_html(b64_string: Union[str, bytes]) -> str ⚓︎

Return an img tag given a base64-jpeg-image-string

Source code in libs/fmts/fmts/__init__.py
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
def base64_jpg_html(b64_string: Union[str, bytes]) -> str:
    """Return an img tag given a base64-jpeg-image-string"""
    try:
        if isinstance(b64_string, bytes):
            b64_string = b64_string.decode("utf-8")
    except UnicodeDecodeError as ude:
        raise ValueError(
            "bytes given instead of string;\n"
            f"tried to decode but got UnicodeDecodeError:\n{str(ude)}"
        ) from ude
    return f'<img src="data:image/jpeg;base64,{str(b64_string)}">'

fmts.binstr(number: int) -> str ⚓︎

Convert an integer to a binary string

Parameters:

Name Type Description Default
number int

Number to convert

required

Returns:

Name Type Description
str str

binary string for the given number

Examples:

>>> binstr(200)
'11001000'
>>> binstr(10)
'1010'
Source code in libs/fmts/fmts/__init__.py
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def binstr(number: int) -> str:
    """Convert an integer to a binary string

    Args:
        number (int): Number to convert

    Returns:
        str: binary string for the given number

    Examples:
        >>> binstr(200)
        '11001000'
        >>> binstr(10)
        '1010'

    """
    return bin(number)[2:]

fmts.body_contents(html_string: str) -> List[str] ⚓︎

Parse the innertext for body tags in an html string

Parameters:

Name Type Description Default
html_string str

html to parse

required

Returns:

Name Type Description
str List[str]

the inner text for the body tags

Examples:

>>> html_string = '<html><body>hello</body></html>'
>>> body_contents(html_string)
['hello']
Source code in libs/fmts/fmts/__init__.py
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
def body_contents(html_string: str) -> List[str]:
    r"""Parse the innertext for body tags in an html string

    Args:
        html_string (str): html to parse

    Returns:
        str: the inner text for the body tags

    Examples:
        >>> html_string = '<html><body>hello</body></html>'
        >>> body_contents(html_string)
        ['hello']

    """
    return re.findall("<body>(.*?)</body>", html_string, re.DOTALL)

fmts.bytes2str(bites: bytes, encoding: str = 'utf-8') -> str ⚓︎

Convert bytes to a string

Parameters:

Name Type Description Default
bites bytes

bytes to convert to string

required
encoding str

encoding as a string; defaults to 'utf-8'

'utf-8'

Returns:

Name Type Description
str str

The bytes as a string

Source code in libs/fmts/fmts/__init__.py
127
128
129
130
131
132
133
134
135
136
137
138
def bytes2str(bites: bytes, encoding: str = "utf-8") -> str:
    """Convert bytes to a string

    Args:
        bites: bytes to convert to string
        encoding (str): encoding as a string; defaults to 'utf-8'

    Returns:
        str: The bytes as a string

    """
    return bites.decode(encoding)

fmts.camel2kebab(string: AnyStr) -> AnyStr ⚓︎

Convert a given camelCase string to kebab-case

Examples:

>>> camel2kebab('camelCase')
'camel-case'
>>> camel2kebab(b'camelCase')
b'camel-case'
Source code in libs/fmts/fmts/__init__.py
412
413
414
415
416
417
418
419
420
421
422
def camel2kebab(string: AnyStr) -> AnyStr:
    """Convert a given camelCase string to kebab-case

    Examples:
        >>> camel2kebab('camelCase')
        'camel-case'
        >>> camel2kebab(b'camelCase')
        b'camel-case'

    """
    return snake2kebab(camel2snake(string))

fmts.camel2pascal(string: AnyStr) -> AnyStr ⚓︎

Convert a given camelCase string to PascalCase

Examples:

>>> camel2pascal('camelCase')
'CamelCase'
>>> camel2pascal(b'camelCase')
b'CamelCase'
Source code in libs/fmts/fmts/__init__.py
359
360
361
362
363
364
365
366
367
368
369
def camel2pascal(string: AnyStr) -> AnyStr:
    """Convert a given camelCase string to PascalCase

    Examples:
        >>> camel2pascal('camelCase')
        'CamelCase'
        >>> camel2pascal(b'camelCase')
        b'CamelCase'

    """
    return _camel2pascal(string)

fmts.camel2snake(string: str) -> str ⚓︎

Convert a 'camelCase' string to a 'snake_case' string

Parameters:

Name Type Description Default
string str

a camelCase string

required

Returns:

Type Description
str

snake_case string

Examples:

>>> camel2snake('camelCase')
'camel_case'
>>> camel2snake(b'camelCase')
b'camel_case'
>>> camel2snake('PascalCase')
'pascal_case'
Source code in libs/fmts/fmts/__init__.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
@anystr2anystr
def camel2snake(string: str) -> str:
    """Convert a 'camelCase' string to a 'snake_case' string

    Args:
        string (str): a camelCase string

    Returns:
        snake_case string

    Examples:
        >>> camel2snake('camelCase')
        'camel_case'
        >>> camel2snake(b'camelCase')
        b'camel_case'
        >>> camel2snake('PascalCase')
        'pascal_case'

    """
    return ALL_CAP_RE.sub(r"\1_\2", FIRST_CAP_RE.sub(r"\1_\2", string)).lower()

fmts.camel_characters_set() -> Set[str] cached ⚓︎

Return a set of all the characters that are allowed in camel case

Examples:

>>> CAMEL_CHARACTERS
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
>>> camel_characters_set() == {c for c in CAMEL_CHARACTERS}
True
Source code in libs/fmts/fmts/__init__.py
141
142
143
144
145
146
147
148
149
150
151
152
@lru_cache(maxsize=1)
def camel_characters_set() -> Set[str]:
    """Return a set of all the characters that are allowed in camel case

    Examples:
        >>> CAMEL_CHARACTERS
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
        >>> camel_characters_set() == {c for c in CAMEL_CHARACTERS}
        True

    """
    return set(CAMEL_CHARACTERS)

fmts.carrots(string: str) -> str ⚓︎

Add carrots on a line below given a string

Parameters:

Name Type Description Default
string str

Input string to under-carrot

required

Returns:

Type Description
str

'carrot-ed-scored' string

Examples:

>>> carrots("A TITLE")
'A TITLE\n^^^^^^^'
>>> print(carrots("A TITLE"))
A TITLE
^^^^^^^
Source code in libs/fmts/fmts/__init__.py
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
@anystr2anystr
def carrots(string: str) -> str:
    r"""Add carrots on a line below given a string

    Args:
        string: Input string to under-carrot

    Returns:
        'carrot-ed-scored' string

    Examples:
        >>> carrots("A TITLE")
        'A TITLE\n^^^^^^^'
        >>> print(carrots("A TITLE"))
        A TITLE
        ^^^^^^^

    """
    return "\n".join([string, "^" * longest_line(string)])

fmts.dedent(string: str) -> str ⚓︎

Dedent a string

Parameters:

Name Type Description Default
string str

Input string to dedent

required

Returns:

Type Description
str

Unindented string

Examples:

>>> s = '    this is a string'
>>> dedent(s)
'this is a string'
>>> s = '        this is a string'
>>> dedent(s)
'    this is a string'
>>> s = "    this is a string\n    with 2 lines"
>>> print(dedent(s))
this is a string
with 2 lines
Source code in libs/fmts/fmts/__init__.py
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
@anystr2anystr
def dedent(string: str) -> str:
    r"""Dedent a string

    Args:
        string: Input string to dedent

    Returns:
        Unindented string

    Examples:
        >>> s = '    this is a string'
        >>> dedent(s)
        'this is a string'
        >>> s = '        this is a string'
        >>> dedent(s)
        '    this is a string'
        >>> s = "    this is a string\n    with 2 lines"
        >>> print(dedent(s))
        this is a string
        with 2 lines

    """
    return "\n".join(
        s if not s.startswith("    ") else s[4:] for s in string.split("\n")
    )

fmts.dos2unix(string: str) -> str ⚓︎

Replace CRLF line endings with LF line endings for a given string

Examples:

>>> dos2unix('hello\r\nworld')
'hello\nworld'
>>> type(b'hello\r\nworld')
<class 'bytes'>
>>> dos2unix(b'hello\r\nworld')
b'hello\nworld'
>>> type(dos2unix(b'hello\r\nworld'))
<class 'bytes'>
Source code in libs/fmts/fmts/__init__.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
@anystr2anystr
def dos2unix(string: str) -> str:
    r"""Replace CRLF line endings with LF line endings for a given string

    Examples:
        >>> dos2unix('hello\r\nworld')
        'hello\nworld'
        >>> type(b'hello\r\nworld')
        <class 'bytes'>
        >>> dos2unix(b'hello\r\nworld')
        b'hello\nworld'
        >>> type(dos2unix(b'hello\r\nworld'))
        <class 'bytes'>

    """
    return string.replace("\r\n", "\n")

fmts.dseconds(ti: Union[float, int], tf: Union[float, int]) -> str ⚓︎

Format time duration given initial and final timestamps in seconds

Parameters:

Name Type Description Default
ti Union[float, int]

Initial time in seconds

required
tf Union[float, int]

Final time in seconds

required

Returns:

Name Type Description
str str

Formatted time duration string readable by humans

Examples:

Less than or equal to one second

>>> for i in range(0, 10, 2):
...     (10**-i, dseconds(0, 10**(-i)))
...
(1, '1.000 sec')
(0.01, '10.000 ms')
(0.0001, '100.000 μs')
(1e-06, '1.000 μs')
(1e-08, '10.000 ns')

Greater than or equal to one second

>>> for i in range(0, 5):
...     (f"{10**i} seconds", dseconds(0, 10**i))
...
('1 seconds', '1.000 sec')
('10 seconds', '10.000 sec')
('100 seconds', '01:40 (mm:ss)')
('1000 seconds', '16:40 (mm:ss)')
('10000 seconds', '02:46:40 (hh:mm:ss)')
Source code in libs/fmts/fmts/__init__.py
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def dseconds(ti: Union[float, int], tf: Union[float, int]) -> str:
    """Format time duration given initial and final timestamps in seconds

    Args:
        ti: Initial time in seconds
        tf: Final time in seconds

    Returns:
        str: Formatted time duration string readable by humans

    Examples:
        Less than or equal to one second

        >>> for i in range(0, 10, 2):
        ...     (10**-i, dseconds(0, 10**(-i)))
        ...
        (1, '1.000 sec')
        (0.01, '10.000 ms')
        (0.0001, '100.000 μs')
        (1e-06, '1.000 μs')
        (1e-08, '10.000 ns')

        Greater than or equal to one second

        >>> for i in range(0, 5):
        ...     (f"{10**i} seconds", dseconds(0, 10**i))
        ...
        ('1 seconds', '1.000 sec')
        ('10 seconds', '10.000 sec')
        ('100 seconds', '01:40 (mm:ss)')
        ('1000 seconds', '16:40 (mm:ss)')
        ('10000 seconds', '02:46:40 (hh:mm:ss)')

    """
    return nseconds(abs(tf - ti))

fmts.ensure_trailing_newline(string: AnyStr) -> AnyStr ⚓︎

Return a string that has only one trailing new line

Examples:

>>> ensure_trailing_newline("foo")
'foo\n'
>>> ensure_trailing_newline('foo\n')
'foo\n'
>>> ensure_trailing_newline("foo\n\n")
'foo\n'
>>> ensure_trailing_newline(b'foo')
b'foo\n'
>>> ensure_trailing_newline(b'foo\n')
b'foo\n'
>>> ensure_trailing_newline(b'foo\n\n')
b'foo\n'
Source code in libs/fmts/fmts/__init__.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
def ensure_trailing_newline(string: AnyStr) -> AnyStr:
    r"""Return a string that has only one trailing new line

    Examples:
        >>> ensure_trailing_newline("foo")
        'foo\n'
        >>> ensure_trailing_newline('foo\n')
        'foo\n'
        >>> ensure_trailing_newline("foo\n\n")
        'foo\n'
        >>> ensure_trailing_newline(b'foo')
        b'foo\n'
        >>> ensure_trailing_newline(b'foo\n')
        b'foo\n'
        >>> ensure_trailing_newline(b'foo\n\n')
        b'foo\n'

    """
    if isinstance(string, bytes):
        return string.rstrip(b"\n") + b"\n"
    return "{}\n".format(string.strip("\n"))

fmts.ensure_utf8(string: Union[str, bytes]) -> str ⚓︎

Return a string that ensured to be utf-8.

This is often needed for those rare cases where some weird non-unicode character or escape sequence is present within a string; This method protects against the possibility of a UnicodeDecodeError.

Parameters:

Name Type Description Default
string Union[str, bytes]

A string which you/one would like the unicode version of

required

Returns:

Type Description
str

The unicode-encoded version of a string

Examples:

>>> ensure_utf8('hello')
'hello'
>>> ensure_utf8(b'hello')
'hello'
>>> latin_bytes_with_weird_characters = b'hello\xc3\xa9'
>>> latin_string = ensure_utf8(latin_bytes_with_weird_characters)
>>> latin_string
'helloé'
>>> problem_bytes = b'hello\x00'
>>> problem_bytes_utf8 = ensure_utf8(problem_bytes)
>>> problem_bytes_utf8
'hello\x00'
>>> ensure_utf8('hello\x00')
'hello\x00'
>>> ensure_utf8(b'hello\x00')
'hello\x00'
Source code in libs/fmts/fmts/__init__.py
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
def ensure_utf8(string: Union[str, bytes]) -> str:
    """Return a string that ensured to be utf-8.

    This is often needed for those rare cases where some weird non-unicode
    character or escape sequence is present within a string; This method
    protects against the possibility of a UnicodeDecodeError.

    Args:
        string: A string which you/one would like the unicode version of

    Returns:
        The unicode-encoded version of a string

    Examples:
        >>> ensure_utf8('hello')
        'hello'
        >>> ensure_utf8(b'hello')
        'hello'
        >>> latin_bytes_with_weird_characters = b'hello\\xc3\\xa9'
        >>> latin_string = ensure_utf8(latin_bytes_with_weird_characters)
        >>> latin_string
        'helloé'
        >>> problem_bytes = b'hello\\x00'
        >>> problem_bytes_utf8 = ensure_utf8(problem_bytes)
        >>> problem_bytes_utf8
        'hello\\x00'
        >>> ensure_utf8('hello\\x00')
        'hello\\x00'
        >>> ensure_utf8(b'hello\\x00')
        'hello\\x00'

    """
    if isinstance(string, bytes):
        try:
            return str(string, encoding="utf-8")
        except UnicodeDecodeError:
            return str(string, encoding="utf-8", errors="ignore")
        except TypeError:
            pass
    return str(string)

fmts.enum_strings(strings: List[str], numsep: str = ')') -> Iterable[str] ⚓︎

Return a generator with enumerated strings

Returns:

Type Description
Iterable[str]

Generator[str]: Generator with enumerated strings

Examples:

>>> list(enum_strings(list(map(str, range(5)))))
['1) 0', '2) 1', '3) 2', '4) 3', '5) 4']
Source code in libs/fmts/fmts/__init__.py
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
def enum_strings(strings: List[str], numsep: str = ")") -> Iterable[str]:
    """Return a generator with enumerated strings

    Returns:
        Generator[str]: Generator with enumerated strings

    Examples:
        >>> list(enum_strings(list(map(str, range(5)))))
        ['1) 0', '2) 1', '3) 2', '4) 3', '5) 4']

    """
    _count = len(str(len(strings)))
    return (
        f"{str(ix).zfill(_count)}{numsep} {s}" for ix, s in enumerate(strings, start=1)
    )

fmts.filesize_str(filepath: str) -> str ⚓︎

Get the human readable filesize string for a file given its path

Parameters:

Name Type Description Default
filepath str

path to file

required

Returns:

Name Type Description
str str

Size of the file

Raises:

Type Description
FileNotFoundError

If the given fspath does not exist

Examples:

>>> fspath = "filesize_str.doctest.txt"
>>> with open(fspath, "w") as f:
...     f.write("dummy file with some stuff")
26
>>> filesize_str(fspath)
'26.0 bytes'
>>> from os import remove; remove(fspath)
Source code in libs/fmts/fmts/__init__.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def filesize_str(filepath: str) -> str:
    """Get the human readable filesize string for a file given its path

    Args:
        filepath (str): path to file

    Returns:
        str: Size of the file

    Raises:
        FileNotFoundError: If the given fspath does not exist

    Examples:
        >>> fspath = "filesize_str.doctest.txt"
        >>> with open(fspath, "w") as f:
        ...     f.write("dummy file with some stuff")
        26
        >>> filesize_str(fspath)
        '26.0 bytes'
        >>> from os import remove; remove(fspath)

    """
    if path.isfile(filepath):
        file_info = stat(filepath)
        return nbytes_str(file_info.st_size)
    raise FileNotFoundError(filepath)  # pragma: no cover

fmts.indent(string: AnyStr, prefix: str = ' ', predicate: Optional[Callable[[str], bool]] = None) -> AnyStr ⚓︎

Indent a string a given number of spaces

Parameters:

Name Type Description Default
string AnyStr

string to indent

required
prefix str

prefix to use for indentation; defaults to 4 spaces

' '
predicate Optional[Callable[[str], bool]]

Optional predicate to determine whether to indent a line;

None

Returns:

Type Description
AnyStr

Indented string

Examples:

>>> s = "this is a string"
>>> indent(s)
'    this is a string'
>>> s = "this is a\nmultiline string"
>>> indent(s)
'    this is a\n    multiline string'
>>> print(indent(s))
    this is a
    multiline string
>>> s = "this is a\nmultiline string"
>>> print(indent(s, '  '))
  this is a
  multiline string
>>> indent(b'this is a string')
b'    this is a string'
Source code in libs/fmts/fmts/__init__.py
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
def indent(
    string: AnyStr,
    prefix: str = "    ",
    predicate: Optional[Callable[[str], bool]] = None,
) -> AnyStr:
    r"""Indent a string a given number of spaces

    Args:
        string: string to indent
        prefix: prefix to use for indentation; defaults to 4 spaces
        predicate: Optional predicate to determine whether to indent a line;

    Returns:
        Indented string

    Examples:
        >>> s = "this is a string"
        >>> indent(s)
        '    this is a string'
        >>> s = "this is a\nmultiline string"
        >>> indent(s)
        '    this is a\n    multiline string'
        >>> print(indent(s))
            this is a
            multiline string
        >>> s = "this is a\nmultiline string"
        >>> print(indent(s, '  '))
          this is a
          multiline string
        >>> indent(b'this is a string')
        b'    this is a string'

    """
    if isinstance(string, bytes):
        return indent(string.decode("utf-8"), prefix, predicate).encode("utf-8")
    return _indent(string, prefix, predicate)

fmts.is_dunder(string: str) -> bool ⚓︎

Return True if a string is 'dunder' (starts and ends with '__')

Parameters:

Name Type Description Default
string str

String to check

required

Returns:

Name Type Description
bool bool

True if is a dunder

Examples:

>>> is_dunder("__dunder__")
True
>>> is_dunder("not_dunder")
False
Source code in libs/fmts/fmts/__init__.py
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
def is_dunder(string: str) -> bool:
    """Return True if a string is 'dunder' (starts and ends with '__')

    Args:
        string (str): String to check

    Returns:
        bool: True if is a dunder

    Examples:
        >>> is_dunder("__dunder__")
        True
        >>> is_dunder("not_dunder")
        False

    """
    return string.startswith("__") and string.endswith("__")

fmts.is_identifier(string: str) -> bool ⚓︎

Return True if a string is a valid python identifier; False otherwise

Parameters:

Name Type Description Default
string str

String (likely to be used as a key) to check

required

Returns:

Name Type Description
bool bool

True if is an identifier

Examples:

>>> is_identifier("herm")
True
>>> is_identifier("something that contains spaces")
False
>>> is_identifier("import")
False
>>> is_identifier("something.with.periods")
False
>>> is_identifier("astring-with-dashes")
False
>>> is_identifier("astring_with_underscores")
True
>>> is_identifier(b"astring_with_underscores")
True
>>> is_identifier(123)
False
Source code in libs/fmts/fmts/__init__.py
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
@anystr
def is_identifier(string: str) -> bool:
    """Return True if a string is a valid python identifier; False otherwise

    Args:
        string (str): String (likely to be used as a key) to check

    Returns:
        bool: True if is an identifier

    Examples:
        >>> is_identifier("herm")
        True
        >>> is_identifier("something that contains spaces")
        False
        >>> is_identifier("import")
        False
        >>> is_identifier("something.with.periods")
        False
        >>> is_identifier("astring-with-dashes")
        False
        >>> is_identifier("astring_with_underscores")
        True
        >>> is_identifier(b"astring_with_underscores")
        True
        >>> is_identifier(123)
        False

    """
    if not isinstance(string, str):
        return False
    if not string.isidentifier():
        return False
    return not iskeyword(string)

fmts.is_snake(string: AnyStr) -> bool ⚓︎

Check if a given string is snake_case

Parameters:

Name Type Description Default
string AnyStr

string to check

required

Returns:

Type Description
bool

is_snake('snake_case')

bool

True

bool

is_snake('kebab-case')

bool

False

bool

is_snake(b'snake_case')

bool

True

bool

is_snake(b'kebab-case')

bool

False

Source code in libs/fmts/fmts/__init__.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@anystr
def is_snake(string: AnyStr) -> bool:
    """Check if a given string is snake_case

    Args:
        string: string to check

    Returns:
        >>> is_snake('snake_case')
        True
        >>> is_snake('kebab-case')
        False
        >>> is_snake(b'snake_case')
        True
        >>> is_snake(b'kebab-case')
        False

    """
    return all(c in snake_characters_set() for c in set(string))

fmts.isidentifier(string: AnyStr) -> bool ⚓︎

Return True if a string is a valid python identifier; False otherwise

Parameters:

Name Type Description Default
string str

String (likely to be used as a key) to check

required

Returns:

Name Type Description
bool bool

True if is an identifier

Examples:

>>> isidentifier("herm")
True
>>> isidentifier("something that contains spaces")
False
>>> isidentifier("import")
False
>>> isidentifier("something.with.periods")
False
>>> isidentifier("astring-with-dashes")
False
>>> isidentifier("astring_with_underscores")
True
>>> isidentifier(123)
False
Source code in libs/fmts/fmts/__init__.py
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
def isidentifier(string: AnyStr) -> bool:
    """Return True if a string is a valid python identifier; False otherwise

    Args:
        string (str): String (likely to be used as a key) to check

    Returns:
        bool: True if is an identifier

    Examples:
        >>> isidentifier("herm")
        True
        >>> isidentifier("something that contains spaces")
        False
        >>> isidentifier("import")
        False
        >>> isidentifier("something.with.periods")
        False
        >>> isidentifier("astring-with-dashes")
        False
        >>> isidentifier("astring_with_underscores")
        True
        >>> isidentifier(123)
        False

    """
    return is_identifier(string)

fmts.kebab2camel(string: AnyStr) -> AnyStr ⚓︎

Convert a given kebab-case string to camelCase

Examples:

>>> kebab2camel('kebab-case')
'kebabCase'
>>> kebab2camel(b'kebab-case')
b'kebabCase'
Source code in libs/fmts/fmts/__init__.py
399
400
401
402
403
404
405
406
407
408
409
def kebab2camel(string: AnyStr) -> AnyStr:
    """Convert a given kebab-case string to camelCase

    Examples:
        >>> kebab2camel('kebab-case')
        'kebabCase'
        >>> kebab2camel(b'kebab-case')
        b'kebabCase'

    """
    return snake2camel(kebab2snake(string))

fmts.kebab2pascal(string: AnyStr) -> AnyStr ⚓︎

Convert a given kebab-case string to PascalCase

Examples:

>>> kebab2pascal('kebab-case')
'KebabCase'
>>> kebab2pascal(b'kebab-case')
b'KebabCase'
Source code in libs/fmts/fmts/__init__.py
372
373
374
375
376
377
378
379
380
381
382
383
@anystr2anystr
def kebab2pascal(string: AnyStr) -> AnyStr:
    """Convert a given kebab-case string to PascalCase

    Examples:
        >>> kebab2pascal('kebab-case')
        'KebabCase'
        >>> kebab2pascal(b'kebab-case')
        b'KebabCase'

    """
    return snake2pascal(kebab2snake(string))

fmts.kebab2snake(string: AnyStr) -> AnyStr ⚓︎

Convert a given kebab-case string to snake_case

Parameters:

Name Type Description Default
string AnyStr

kebab case string

required

Returns:

Type Description
AnyStr

kebab2snake('kebab-case')

AnyStr

'kebab_case'

AnyStr

kebab2snake(b'kebab-case')

AnyStr

b'kebab_case'

Source code in libs/fmts/fmts/__init__.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def kebab2snake(string: AnyStr) -> AnyStr:
    """Convert a given kebab-case string to snake_case

    Args:
        string: kebab case string

    Returns:
        >>> kebab2snake('kebab-case')
        'kebab_case'
        >>> kebab2snake(b'kebab-case')
        b'kebab_case'

    """
    if isinstance(string, bytes):
        return string.replace(b"-", b"_")
    return string.replace("-", "_")

fmts.kebab_characters_set() -> Set[str] cached ⚓︎

Return a set of all the characters that are allowed in camel case

Examples:

>>> KEBAB_CHARACTERS
'abcdefghijklmnopqrstuvwxyz0123456789-'
>>> kebab_characters_set() == {c for c in KEBAB_CHARACTERS}
True
Source code in libs/fmts/fmts/__init__.py
155
156
157
158
159
160
161
162
163
164
165
166
@lru_cache(maxsize=1)
def kebab_characters_set() -> Set[str]:
    """Return a set of all the characters that are allowed in camel case

    Examples:
        >>> KEBAB_CHARACTERS
        'abcdefghijklmnopqrstuvwxyz0123456789-'
        >>> kebab_characters_set() == {c for c in KEBAB_CHARACTERS}
        True

    """
    return set(KEBAB_CHARACTERS)

fmts.long_timestamp_string(timestamp_sec: float) -> str ⚓︎

Return a 'long-form' timestamp string given epoch-seconds float

Source code in libs/fmts/fmts/__init__.py
1405
1406
1407
1408
1409
def long_timestamp_string(timestamp_sec: float) -> str:
    """Return a 'long-form' timestamp string given epoch-seconds float"""
    return datetime.fromtimestamp(
        timestamp_sec, tz=timezone(timedelta(hours=-8))
    ).strftime("%A, %d. %B %Y %I:%M%p")

fmts.longest_line(string: Union[str, bytes]) -> int ⚓︎

Return the length of the longest line in a string

Parameters:

Name Type Description Default
string str

String that has either one or more lines

required

Returns:

Name Type Description
int int

The length of the longest line in the string

Examples:

>>> longest_line('hello\nworld')
5
>>> longest_line(b'hello\nworld')
5
>>> longest_line('hello world')
11
>>> longest_line(b'hello world')
11
Source code in libs/fmts/fmts/__init__.py
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
def longest_line(string: Union[str, bytes]) -> int:
    r"""Return the length of the longest line in a string

    Args:
        string (str): String that has either one or more lines

    Returns:
        int: The length of the longest line in the string

    Examples:
        >>> longest_line('hello\nworld')
        5
        >>> longest_line(b'hello\nworld')
        5
        >>> longest_line('hello world')
        11
        >>> longest_line(b'hello world')
        11

    """
    if isinstance(string, bytes):
        if b"\n" in string:
            return max(len(line) for line in string.splitlines(keepends=False))
        return len(string)

    if "\n" in string:
        return max(len(line) for line in string.splitlines(keepends=False))
    return len(string)

fmts.multi_replace(string: str, replacements: Union[List[Tuple[str, str]], List[List[str]], Dict[str, str], ItemsView[str, str]]) -> str ⚓︎

Replace multiple patterns in a string

Parameters:

Name Type Description Default
string str

Strint to apply

required
replacements Union[List[Tuple[str, str]], List[List[str]], Dict[str, str], ItemsView[str, str]]

Replacement combos

required

Returns:

Name Type Description
str str

Input string with all the replacements applied in order

Examples:

Works with a list of lists!

>>> replacements = [['hello', 'goodbye'], ['world', 'earth']]
>>> multi_replace('hello, world', replacements)
'goodbye, earth'

Works with a list of tuples!

>>> replacements = [('hello', 'goodbye'), ('world', 'earth')]
>>> multi_replace('hello, world', replacements)
'goodbye, earth'

Works with a dictionary where all keys and values are strings!

>>> replacements = {'hello': 'goodbye', 'world': 'earth'}
>>> multi_replace('hello, world', replacements)
'goodbye, earth'
>>> replacements = [['hello', 'goodbye'], ['world', 'this', 'will', 'fail']]
>>> try:
...     multi_replace('hello, world', replacements)
... except ValueError:
...     print('ValueError raised')
ValueError raised
Source code in libs/fmts/fmts/__init__.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
def multi_replace(
    string: str,
    replacements: Union[
        List[Tuple[str, str]], List[List[str]], Dict[str, str], ItemsView[str, str]
    ],
) -> str:
    """Replace multiple patterns in a string

    Args:
        string: Strint to apply
        replacements: Replacement combos

    Returns:
        str: Input string with all the replacements applied in order

    Examples:
        Works with a list of lists!

        >>> replacements = [['hello', 'goodbye'], ['world', 'earth']]
        >>> multi_replace('hello, world', replacements)
        'goodbye, earth'

        Works with a list of tuples!

        >>> replacements = [('hello', 'goodbye'), ('world', 'earth')]
        >>> multi_replace('hello, world', replacements)
        'goodbye, earth'

        Works with a dictionary where all keys and values are strings!

        >>> replacements = {'hello': 'goodbye', 'world': 'earth'}
        >>> multi_replace('hello, world', replacements)
        'goodbye, earth'

        >>> replacements = [['hello', 'goodbye'], ['world', 'this', 'will', 'fail']]
        >>> try:
        ...     multi_replace('hello, world', replacements)
        ... except ValueError:
        ...     print('ValueError raised')
        ValueError raised

    """
    if isinstance(replacements, dict):
        return multi_replace(string, replacements.items())
    for rep in replacements:
        if isinstance(rep, list):
            if len(rep) != 2:
                raise ValueError("Replacement must be a list of length 2")
            string = string.replace(rep[0], rep[1])
        else:
            string = string.replace(*rep)
    return string

fmts.nbytes(nbytes: Union[int, float]) -> str ⚓︎

Alias for nbytes_str (for backward compatibility)

Examples:

>>> nbytes(100)
'100.0 bytes'
>>> nbytes(1000)
'1000.0 bytes'
>>> nbytes(10000)
'9.8 KB'
>>> nbytes(100000)
'97.7 KB'
>>> nbytes(1000000)
'976.6 KB'
>>> nbytes(10_000_000)
'9.5 MB'
>>> nbytes(100_000_000)
'95.4 MB'
>>> nbytes(1000000000)
'953.7 MB'
>>> nbytes(10000000000)
'9.3 GB'
>>> nbytes(100000000000)
'93.1 GB'
>>> nbytes(1000000000000)
'931.3 GB'
>>> nbytes(10000000000000)
'9.1 TB'
>>> nbytes(100000000000000)
'90.9 TB'
Source code in libs/fmts/fmts/__init__.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
def nbytes(nbytes: Union[int, float]) -> str:
    """Alias for nbytes_str (for backward compatibility)

    Examples:
        >>> nbytes(100)
        '100.0 bytes'
        >>> nbytes(1000)
        '1000.0 bytes'
        >>> nbytes(10000)
        '9.8 KB'
        >>> nbytes(100000)
        '97.7 KB'
        >>> nbytes(1000000)
        '976.6 KB'
        >>> nbytes(10_000_000)
        '9.5 MB'
        >>> nbytes(100_000_000)
        '95.4 MB'
        >>> nbytes(1000000000)
        '953.7 MB'
        >>> nbytes(10000000000)
        '9.3 GB'
        >>> nbytes(100000000000)
        '93.1 GB'
        >>> nbytes(1000000000000)
        '931.3 GB'
        >>> nbytes(10000000000000)
        '9.1 TB'
        >>> nbytes(100000000000000)
        '90.9 TB'

    """
    return nbytes_str(nbytes)

fmts.nbytes_str(nbytes: Union[int, float]) -> str ⚓︎

Format nbytesber of bytes to human readable form

Parameters:

Name Type Description Default
nbytes Union[int, float]

number of bytes

required

Returns:

Name Type Description
str str

nbytesber of bytes formatted

Raises:

Type Description
ValueError

If given number of bytes is invalid/negative

Examples:

>>> nbytes_str(100)
'100.0 bytes'
>>> nbytes_str(1000)
'1000.0 bytes'
>>> nbytes_str(10000)
'9.8 KB'
>>> nbytes_str(100000)
'97.7 KB'
>>> nbytes_str(1000000)
'976.6 KB'
>>> nbytes_str(10_000_000)
'9.5 MB'
>>> nbytes_str(100_000_000)
'95.4 MB'
>>> nbytes_str(1000000000)
'953.7 MB'
>>> nbytes_str(10000000000)
'9.3 GB'
>>> nbytes_str(100000000000)
'93.1 GB'
>>> nbytes_str(1000000000000)
'931.3 GB'
>>> nbytes_str(10000000000000)
'9.1 TB'
>>> nbytes_str(100000000000000)
'90.9 TB'
>>> nbytes_str(-100000000000)
'-93.1 GB'
Source code in libs/fmts/fmts/__init__.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
def nbytes_str(nbytes: Union[int, float]) -> str:
    """Format nbytesber of bytes to human readable form

    Args:
        nbytes: number of bytes

    Returns:
        str: nbytesber of bytes formatted

    Raises:
        ValueError: If given number of bytes is invalid/negative

    Examples:
        >>> nbytes_str(100)
        '100.0 bytes'
        >>> nbytes_str(1000)
        '1000.0 bytes'
        >>> nbytes_str(10000)
        '9.8 KB'
        >>> nbytes_str(100000)
        '97.7 KB'
        >>> nbytes_str(1000000)
        '976.6 KB'
        >>> nbytes_str(10_000_000)
        '9.5 MB'
        >>> nbytes_str(100_000_000)
        '95.4 MB'
        >>> nbytes_str(1000000000)
        '953.7 MB'
        >>> nbytes_str(10000000000)
        '9.3 GB'
        >>> nbytes_str(100000000000)
        '93.1 GB'
        >>> nbytes_str(1000000000000)
        '931.3 GB'
        >>> nbytes_str(10000000000000)
        '9.1 TB'
        >>> nbytes_str(100000000000000)
        '90.9 TB'
        >>> nbytes_str(-100000000000)
        '-93.1 GB'

    """
    if nbytes < 0:
        return f"-{nbytes_str(abs(nbytes))}"
    for x in ["bytes", "KB", "MB", "GB", "TB"]:
        if nbytes < 1024.0 or x == "TB":
            _str = f"{nbytes:3.1f} {x}"
            return _str
        nbytes /= 1024.0
    raise ValueError(f"Invalid number of bytes: {nbytes}")  # pragma: no cover

fmts.nseconds(nsec: float) -> str ⚓︎

Format a number of seconds as a human readable string

Formats nsec if t2 is None as a string; Calculates the time and formats the time t2-nsec if t2 is not None.

Parameters:

Name Type Description Default
nsec float

Timestamp epoch seconds

required

Returns:

Name Type Description
str str

Formatted time duration string readable by humans

Examples:

Less than or equal to one second

>>> for i in range(0, 10, 2):
...     (10**-i, nseconds(10**(-i)))
...
(1, '1.000 sec')
(0.01, '10.000 ms')
(0.0001, '100.000 μs')
(1e-06, '1.000 μs')
(1e-08, '10.000 ns')

Greater than or equal to one second

>>> for i in range(0, 5):
...     (f"{10**i} seconds", nseconds(10**i))
...
('1 seconds', '1.000 sec')
('10 seconds', '10.000 sec')
('100 seconds', '01:40 (mm:ss)')
('1000 seconds', '16:40 (mm:ss)')
('10000 seconds', '02:46:40 (hh:mm:ss)')
>>> nseconds(-60)
'01:00 (mm:ss)'
>>> nseconds(60)
'01:00 (mm:ss)'
>>> nseconds(0)
'0 sec'
Source code in libs/fmts/fmts/__init__.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
def nseconds(nsec: float) -> str:
    """Format a number of seconds as a human readable string

    Formats nsec if t2 is None as a string; Calculates the time and formats
    the time t2-nsec if t2 is not None.

    Args:
        nsec (float): Timestamp epoch seconds

    Returns:
        str: Formatted time duration string readable by humans

    Examples:
        Less than or equal to one second
        >>> for i in range(0, 10, 2):
        ...     (10**-i, nseconds(10**(-i)))
        ...
        (1, '1.000 sec')
        (0.01, '10.000 ms')
        (0.0001, '100.000 μs')
        (1e-06, '1.000 μs')
        (1e-08, '10.000 ns')

        Greater than or equal to one second
        >>> for i in range(0, 5):
        ...     (f"{10**i} seconds", nseconds(10**i))
        ...
        ('1 seconds', '1.000 sec')
        ('10 seconds', '10.000 sec')
        ('100 seconds', '01:40 (mm:ss)')
        ('1000 seconds', '16:40 (mm:ss)')
        ('10000 seconds', '02:46:40 (hh:mm:ss)')
        >>> nseconds(-60)
        '01:00 (mm:ss)'
        >>> nseconds(60)
        '01:00 (mm:ss)'
        >>> nseconds(0)
        '0 sec'

    """
    if nsec < 0:
        return nseconds(abs(nsec))
    elif nsec == 0.0:
        return "0 sec"
    elif 0.000001 > nsec >= 0.000000001:
        return f"{(10 ** 9) * nsec:.3f} ns"
    elif 0.001 > nsec >= 0.000001:
        return f"{(10 ** 6) * nsec:.3f} μs"
    elif 1 > nsec >= 0.001:
        return f"{(10 ** 3) * nsec:.3f} ms"
    elif nsec < 60:
        return f"{nsec:.3f} sec"
    elif nsec < 3600:
        minutes = nsec // 60
        nsec %= 60
        return f"{minutes:02d}:{nsec:02d} (mm:ss)"
    else:
        hours = nsec // (60 * 60)
        nsec %= 60 * 60
        minutes = nsec // 60
        nsec %= 60
        return f"{hours:02d}:{minutes:02d}:{nsec:02d} (hh:mm:ss)"

fmts.overscore(string: str) -> str ⚓︎

Add underscores on a line above the given string

Parameters:

Name Type Description Default
string str

Input string to overscore

required

Returns:

Type Description
str

'Over-scored' string

Examples:

>>> overscore("A TITLE")
'_______\nA TITLE'
>>> print(overscore("A TITLE"))
_______
A TITLE
Source code in libs/fmts/fmts/__init__.py
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
@anystr2anystr
def overscore(string: str) -> str:
    r"""Add underscores on a line above the given string

    Args:
        string: Input string to overscore

    Returns:
        'Over-scored' string

    Examples:
        >>> overscore("A TITLE")
        '_______\nA TITLE'
        >>> print(overscore("A TITLE"))
        _______
        A TITLE

    """
    return "\n".join(["_" * longest_line(string), string])

fmts.overscore_carrots(string: str) -> str ⚓︎

Add underscores on a line above a string and carrots on a line below

Parameters:

Name Type Description Default
string str

Input string to overscore and carrot

required

Returns:

Type Description
str

'Over-scored' and carroted string

Examples:

>>> overscore_carrots("A TITLE")
'_______\nA TITLE\n^^^^^^^'
>>> print(overscore_carrots("A TITLE"))
_______
A TITLE
^^^^^^^
Source code in libs/fmts/fmts/__init__.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
@anystr2anystr
def overscore_carrots(string: str) -> str:
    r"""Add underscores on a line above a string and carrots on a line below

    Args:
        string: Input string to overscore and carrot

    Returns:
        'Over-scored' and carroted string

    Examples:
        >>> overscore_carrots("A TITLE")
        '_______\nA TITLE\n^^^^^^^'
        >>> print(overscore_carrots("A TITLE"))
        _______
        A TITLE
        ^^^^^^^

    """
    _n = longest_line(string)
    return "\n".join(["_" * _n, string, "^" * _n])

fmts.pascal2camel(string: str) -> str ⚓︎

Convert a 'PascalCase' string to a 'camelCase' string

Parameters:

Name Type Description Default
string str

a PascalCase string

required

Returns:

Type Description
str

camelCase string

Examples:

>>> pascal2camel('PascalCase')
'pascalCase'
>>> pascal2camel(b'PascalCase')
b'pascalCase'
Source code in libs/fmts/fmts/__init__.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
@anystr2anystr
def pascal2camel(string: str) -> str:
    """Convert a 'PascalCase' string to a 'camelCase' string

    Args:
        string (str): a PascalCase string

    Returns:
        camelCase string

    Examples:
        >>> pascal2camel('PascalCase')
        'pascalCase'
        >>> pascal2camel(b'PascalCase')
        b'pascalCase'

    """
    return string[0].lower() + string[1:]

fmts.pascal2kebab(string: AnyStr) -> AnyStr ⚓︎

Convert a given PascalCase string to kebab-case

Examples:

>>> pascal2kebab('PascalCase')
'pascal-case'
>>> pascal2kebab(b'PascalCase')
b'pascal-case'
Source code in libs/fmts/fmts/__init__.py
386
387
388
389
390
391
392
393
394
395
396
def pascal2kebab(string: AnyStr) -> AnyStr:
    """Convert a given PascalCase string to kebab-case

    Examples:
        >>> pascal2kebab('PascalCase')
        'pascal-case'
        >>> pascal2kebab(b'PascalCase')
        b'pascal-case'

    """
    return snake2kebab(pascal2snake(string))

fmts.pascal2snake(string: AnyStr) -> AnyStr ⚓︎

Convert a given PascalCase string to snake_case

Examples:

>>> pascal2snake('PascalCase')
'pascal_case'
>>> pascal2snake(b'PascalCase')
b'pascal_case'
Source code in libs/fmts/fmts/__init__.py
331
332
333
334
335
336
337
338
339
340
341
342
@anystr2anystr
def pascal2snake(string: AnyStr) -> AnyStr:
    """Convert a given PascalCase string to snake_case

    Examples:
        >>> pascal2snake('PascalCase')
        'pascal_case'
        >>> pascal2snake(b'PascalCase')
        b'pascal_case'

    """
    return camel2snake(pascal2camel(string))

fmts.printable_characters_set() -> Set[str] cached ⚓︎

Return set of all printable characters

Returns:

Type Description
Set[str]

Set[str]: set of all printable characters

Examples:

>>> printable_characters_set() == {c for c in printable}
True
Source code in libs/fmts/fmts/__init__.py
169
170
171
172
173
174
175
176
177
178
179
180
181
@lru_cache(maxsize=1)
def printable_characters_set() -> Set[str]:
    """Return set of all printable characters

    Returns:
        Set[str]: set of all printable characters

    Examples:
        >>> printable_characters_set() == {c for c in printable}
        True

    """
    return set(printable)

fmts.randhexstr(length: int = 8) -> str ⚓︎

Return a random hex string

Parameters:

Name Type Description Default
length int

length of desired random string (defaults to 4)

8

Returns:

Name Type Description
str str

random hex string

Examples:

>>> a = randhexstr()
>>> isinstance(a, str)
True
>>> len(a)
8
>>> b = randhexstr(10)
>>> isinstance(b, str)
True
>>> len(b)
10
>>> randhexstr(0)
Traceback (most recent call last):
    ...
ValueError: length must be a positive even number
Source code in libs/fmts/fmts/__init__.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
def randhexstr(length: int = 8) -> str:
    """Return a random hex string

    Args:
        length (int): length of desired random string (defaults to 4)

    Returns:
        str: random hex string

    Examples:
        >>> a = randhexstr()
        >>> isinstance(a, str)
        True
        >>> len(a)
        8
        >>> b = randhexstr(10)
        >>> isinstance(b, str)
        True
        >>> len(b)
        10
        >>> randhexstr(0)
        Traceback (most recent call last):
            ...
        ValueError: length must be a positive even number

    """
    if length % 2 != 0 or length < 1:
        raise ValueError("length must be a positive even number")
    return bytes2str(hexlify(urandom(length // 2)))

fmts.random_string(length: int = 8, hex: bool = False) -> str ⚓︎

Return a random ascii string (length=str_len; default=4)

Examples:

>>> a = random_string()
>>> isinstance(a, str)
True
>>> len(a)
8
>>> a = random_string(12)
>>> isinstance(a, str)
True
>>> len(a)
12
>>> a = random_string(8, hex=True)
>>> isinstance(a, str)
True
>>> len(a)
8
Source code in libs/fmts/fmts/__init__.py
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
def random_string(length: int = 8, hex: bool = False) -> str:
    """Return a random ascii string (length=str_len; default=4)

    Examples:
        >>> a = random_string()
        >>> isinstance(a, str)
        True
        >>> len(a)
        8
        >>> a = random_string(12)
        >>> isinstance(a, str)
        True
        >>> len(a)
        12
        >>> a = random_string(8, hex=True)
        >>> isinstance(a, str)
        True
        >>> len(a)
        8

    """
    if hex:
        return randhexstr(length)
    letters = ascii_lowercase + ascii_uppercase
    return "".join(choice(letters) for _ in range(length))

fmts.rm_b(string: str) -> str ⚓︎

Remove the b'' from binary strings and sub-strings that contain b''

Taken from 'pupy' (Pretty Useful Python (which jesse wrote))

Parameters:

Name Type Description Default
string str

A string surrounded by b'' or a sub-string with b''

required

Returns:

Name Type Description
str str

A string without binary b'' quotes surround it

Examples:

>>> rm_b("b'a_string'")
'a_string'
Source code in libs/fmts/fmts/__init__.py
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
@anystr2anystr
def rm_b(string: str) -> str:
    """Remove the b'' from binary strings and sub-strings that contain b''

    Taken from 'pupy' (Pretty Useful Python (which jesse wrote))

    Args:
        string (str): A string surrounded by b'' or a sub-string with b''

    Returns:
        str: A string without binary b'' quotes surround it

    Examples:
        >>> rm_b("b'a_string'")
        'a_string'

    """
    return re.sub("b'([^']*)'", r"\1", string)

fmts.rm_character(string: str, split_str: str, join_str: str) -> str ⚓︎

Remove a character in a string globally

Parameters:

Name Type Description Default
string str

string to remove characters from

required
split_str str

character to remove

required
join_str str

character to join the split-string on

required

Returns:

Type Description
str

String with the character/string given by split_str removed

Source code in libs/fmts/fmts/__init__.py
882
883
884
885
886
887
888
889
890
891
892
893
894
def rm_character(string: str, split_str: str, join_str: str) -> str:
    """Remove a character in a string globally

    Args:
        string: string to remove characters from
        split_str: character to remove
        join_str: character to join the split-string on

    Returns:
        String with the character/string given by split_str removed

    """
    return join_str.join(el for el in string.split(split_str) if el != "")

fmts.rm_dunderscore(string: str) -> str ⚓︎

Replace n>=2 underscores with a single underscore

Parameters:

Name Type Description Default
string str

String to remove double underscores from

required

Returns:

Type Description
str

String with no adjacent underscores

Examples:

>>> rm_dunderscore('there____are___many____double_______underscores')
'there_are_many_double_underscores'
Source code in libs/fmts/fmts/__init__.py
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
@anystr2anystr
def rm_dunderscore(string: str) -> str:
    """Replace n>=2 underscores with a single underscore

    Args:
        string: String to remove double underscores from

    Returns:
        String with no adjacent underscores

    Examples:
        >>> rm_dunderscore('there____are___many____double_______underscores')
        'there_are_many_double_underscores'

    """
    return rm_character(string=string, split_str="_", join_str="_")

fmts.rm_multilines(string: str) -> str ⚓︎

Remove blank lines from a string

Parameters:

Name Type Description Default
string str

string possibly containing blank lines

required

Returns:

Type Description
str

string without blank lines

Examples:

>>> rm_multilines('hello\n\nworld')
'hello\nworld'
Source code in libs/fmts/fmts/__init__.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
def rm_multilines(string: str) -> str:
    r"""Remove blank lines from a string

    Args:
        string: string possibly containing blank lines

    Returns:
        string without blank lines

    Examples:
        >>> rm_multilines('hello\n\nworld')
        'hello\nworld'

    """
    return "\n".join(
        ll.rstrip() for ll in string.replace("\r\n", "\n").split("\n") if ll.strip()
    )

fmts.rm_u(string: str) -> str ⚓︎

Remove the u'' from unicode strings and sub-strings that contain u''

Parameters:

Name Type Description Default
string str

A string surrounded by u'' or a sub-string with u''

required

Returns:

Name Type Description
str str

A string without unicode u'' quotes surround it

Examples:

>>> a = "u'a_string'"
>>> rm_u(a)
'a_string'
Source code in libs/fmts/fmts/__init__.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
@anystr2anystr
def rm_u(string: str) -> str:
    """Remove the u'' from unicode strings and sub-strings that contain u''

    Args:
        string (str): A string surrounded by u'' or a sub-string with u''

    Returns:
        str:A string without unicode u'' quotes surround it

    Examples:
        >>> a = "u'a_string'"
        >>> rm_u(a)
        'a_string'

    """
    return re.sub("u'([^']*)'", r"\1", string)

fmts.rm_whitespace(string: str, join_str: str = ' ') -> str ⚓︎

Replace n>=2 spaces with a single underscore

Parameters:

Name Type Description Default
join_str str

String to join on; defaults to a space (' ')

' '
string str

String to remove spaces from

required

Returns:

Type Description
str

String with no spaces and underscores where there were spaces

Examples:

>>> rm_whitespace('there are lots of    spaces')
'there are lots of spaces'
>>> rm_whitespace('there are lots of    spaces', join_str='_')
'there_are_lots_of_spaces'
Source code in libs/fmts/fmts/__init__.py
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
def rm_whitespace(string: str, join_str: str = " ") -> str:
    """Replace n>=2 spaces with a single underscore

    Args:
        join_str (str): String to join on; defaults to a space (' ')
        string: String to remove spaces from

    Returns:
        String with no spaces and underscores where there were spaces

    Examples:
        >>> rm_whitespace('there are lots of    spaces')
        'there are lots of spaces'
        >>> rm_whitespace('there are lots of    spaces', join_str='_')
        'there_are_lots_of_spaces'

    """
    return rm_character(string, split_str=" ", join_str=join_str)

fmts.snake2camel(string: AnyStr) -> AnyStr ⚓︎

Convert a given snake_case string to camelCase

Parameters:

Name Type Description Default
string AnyStr

snake case string

required

Returns:

Type Description
AnyStr

snake2camel('camel_case')

AnyStr

'camelCase'

AnyStr

snake2camel(b'camel_case')

AnyStr

b'camelCase'

Source code in libs/fmts/fmts/__init__.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
@anystr2anystr
def snake2camel(string: AnyStr) -> AnyStr:
    """Convert a given snake_case string to camelCase

    Args:
        string: snake case string

    Returns:
        >>> snake2camel('camel_case')
        'camelCase'
        >>> snake2camel(b'camel_case')
        b'camelCase'

    """
    return _snake2camel(string)

fmts.snake2kebab(string: AnyStr) -> AnyStr ⚓︎

Convert a given snake_case string to kebab-case

Parameters:

Name Type Description Default
string AnyStr

snake case string

required

Returns:

Type Description
AnyStr

snake2kebab('kebab_case')

AnyStr

'kebab-case'

AnyStr

snake2kebab(b'kebab_case')

AnyStr

b'kebab-case'

Source code in libs/fmts/fmts/__init__.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def snake2kebab(string: AnyStr) -> AnyStr:
    """Convert a given snake_case string to kebab-case

    Args:
        string: snake case string

    Returns:
        >>> snake2kebab('kebab_case')
        'kebab-case'
        >>> snake2kebab(b'kebab_case')
        b'kebab-case'

    """
    if isinstance(string, bytes):
        return string.replace(b"_", b"-")
    return string.replace("_", "-")

fmts.snake2pascal(string: AnyStr) -> AnyStr ⚓︎

Convert a given snake_case string to PascalCase

Parameters:

Name Type Description Default
string AnyStr

snake case string

required

Returns:

Type Description
AnyStr

PascalCase string

Examples:

>>> snake2pascal('pascal_case')
'PascalCase'
>>> snake2pascal(b'pascal_case')
b'PascalCase'
Source code in libs/fmts/fmts/__init__.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def snake2pascal(string: AnyStr) -> AnyStr:
    """Convert a given snake_case string to PascalCase

    Args:
        string: snake case string

    Returns:
        PascalCase string

    Examples:
        >>> snake2pascal('pascal_case')
        'PascalCase'
        >>> snake2pascal(b'pascal_case')
        b'PascalCase'

    """
    if isinstance(string, bytes):
        return b"".join(x.capitalize() for x in string.split(b"_"))
    return "".join(x.title() for x in string.split("_"))

fmts.space_pad_strings(strings: List[str], justify: str = 'left') -> List[str] ⚓︎

Space pads strings to match the string with the max length

Returns:

Type Description
List[str]

List[str]: List of space-padded strings

Examples:

>>> space_pad_strings(["a", "bb", "ccc"])
['a  ', 'bb ', 'ccc']
>>> space_pad_strings(["a", "bb", "ccc"], justify='right')
['  a', ' bb', 'ccc']
>>> space_pad_strings(["a", "bb", "ccc"], justify='center')
Traceback (most recent call last):
...
ValueError: justify must be 'left' or 'right', not center; case-insensitive
Source code in libs/fmts/fmts/__init__.py
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
def space_pad_strings(strings: List[str], justify: str = "left") -> List[str]:
    """Space pads strings to match the string with the max length

    Returns:
        List[str]: List of space-padded strings

    Examples:
        >>> space_pad_strings(["a", "bb", "ccc"])
        ['a  ', 'bb ', 'ccc']
        >>> space_pad_strings(["a", "bb", "ccc"], justify='right')
        ['  a', ' bb', 'ccc']
        >>> space_pad_strings(["a", "bb", "ccc"], justify='center')
        Traceback (most recent call last):
        ...
        ValueError: justify must be 'left' or 'right', not center; case-insensitive

    """
    _justify = justify.lower()
    if _justify not in ["left", "right"]:
        raise ValueError(
            f"justify must be 'left' or 'right', not {justify}; case-insensitive"
        )
    _max_len = max(len(s) for s in strings)
    if _justify == "right":
        return [s.rjust(_max_len) for s in strings]
    return [s.ljust(_max_len) for s in strings]

fmts.str_is_identifier(string: str) -> bool ⚓︎

Return True if a string is a valid python identifier; False otherwise

Parameters:

Name Type Description Default
string str

String (likely to be used as a key) to check

required

Returns:

Name Type Description
bool bool

True if is an identifier

Examples:

>>> str_is_identifier("howdy")
True
>>> str_is_identifier("class")
False
Source code in libs/fmts/fmts/__init__.py
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
@anystr
def str_is_identifier(string: str) -> bool:
    """Return True if a string is a valid python identifier; False otherwise

    Args:
        string (str): String (likely to be used as a key) to check

    Returns:
        bool: True if is an identifier

    Examples:
        >>> str_is_identifier("howdy")
        True
        >>> str_is_identifier("class")
        False

    """
    return string.isidentifier() and not iskeyword(string)

fmts.string_sanitize(string: str) -> str ⚓︎

Clean up a string

Parameters:

Name Type Description Default
string str

String to sanitize

required

Returns:

Type Description
str

input string sanitized

Examples:

>>> string_sanitize('5/9999((5')
'599995'
>>> string_sanitize('question????,')
'question'
Source code in libs/fmts/fmts/__init__.py
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
def string_sanitize(string: str) -> str:
    """Clean up a string

    Args:
        string (str): String to sanitize

    Returns:
        input string sanitized

    Examples:
        >>> string_sanitize('5/9999((5')
        '599995'
        >>> string_sanitize('question????,')
        'question'

    """
    return strip_non_ascii(re.sub(r"[()\"/;:<>{}`=~|!?,]", "", string).strip("."))

fmts.strip_ascii(string: str) -> str ⚓︎

Remove all ascii characters from a string

Parameters:

Name Type Description Default
string str

string with non-ascii characters

required

Returns:

Type Description
str

string of only the non-ascii characters

Examples:

>>> string_w_non_ascii_chars = 'Three fourths: ¾'
>>> strip_ascii(string_w_non_ascii_chars)
'¾'
Source code in libs/fmts/fmts/__init__.py
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
@anystr2anystr
def strip_ascii(string: str) -> str:
    """Remove all ascii characters from a string

    Args:
        string (str): string with non-ascii characters

    Returns:
        string of only the non-ascii characters

    Examples:
        >>> string_w_non_ascii_chars = 'Three fourths: ¾'
        >>> strip_ascii(string_w_non_ascii_chars)
        '¾'

    """
    return "".join(filter(lambda x: ord(x) > 128, string))

fmts.strip_comments(string: str) -> str ⚓︎

Remove comments from python/shell scripts given the script as a string

Parameters:

Name Type Description Default
string str

string with # comments

required

Returns:

Name Type Description
str str

input string with comments striped out

Examples:

Here is an example of stripping comments from a python-ish script:

>>> python_script_ish = r'''# some encoding
... # this is a comment
... # this is another comment
... print('hello bob')
... print('hello bobert')  # bob is short for bobert
... '''
>>> a = strip_comments(python_script_ish)
>>> a.splitlines(keepends=False)
['', '', '', "print('hello bob')", "print('hello bobert')  "]

Here is an example of stripping comments from a bash/shell-ish script:

>>> bash_script_ish = r'''#!/bin/bash
... # this is a comment
... # this is another comment
... echo "hello"
... echo "hello again" # comment
... '''
>>> a = strip_comments(bash_script_ish)
>>> a.splitlines(keepends=False)
['', '', '', 'echo "hello"', 'echo "hello again" ']
Source code in libs/fmts/fmts/__init__.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
@anystr2anystr
def strip_comments(string: str) -> str:
    """Remove comments from python/shell scripts given the script as a string

    Args:
        string (str): string with `#` comments

    Returns:
        str: input string with comments striped out

    Examples:
        Here is an example of stripping comments from a python-ish script:

        >>> python_script_ish = r'''# some encoding
        ... # this is a comment
        ... # this is another comment
        ... print('hello bob')
        ... print('hello bobert')  # bob is short for bobert
        ... '''
        >>> a = strip_comments(python_script_ish)
        >>> a.splitlines(keepends=False)
        ['', '', '', "print('hello bob')", "print('hello bobert')  "]

        Here is an example of stripping comments from a bash/shell-ish script:

        >>> bash_script_ish = r'''#!/bin/bash
        ... # this is a comment
        ... # this is another comment
        ... echo "hello"
        ... echo "hello again" # comment
        ... '''
        >>> a = strip_comments(bash_script_ish)
        >>> a.splitlines(keepends=False)
        ['', '', '', 'echo "hello"', 'echo "hello again" ']

    """
    filelines = string.splitlines(keepends=False)
    comment_re = re.compile(r'(?:"(?:[^"\\]|\\.)*"|[^"#])*(#|$)')

    def _strip_comments_line(line: str) -> str:
        comment_re_match = comment_re.match(line)
        if comment_re_match:
            return line[: comment_re_match.start(1)]
        return line  # pragma: no cover

    return "\n".join(_strip_comments_line(line) for line in filelines)

fmts.strip_non_ascii(s: str) -> str ⚓︎

Remove all ascii characters from a string

Parameters:

Name Type Description Default
s str

string with non-ascii characters

required

Returns:

Type Description
str

string of only the non-ascii characters

Examples:

>>> string_w_non_ascii_chars = 'Three fourths: ¾'
>>> strip_non_ascii(string_w_non_ascii_chars)
'Three fourths: '
Source code in libs/fmts/fmts/__init__.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
@anystr2anystr
def strip_non_ascii(s: str) -> str:
    """Remove all ascii characters from a string

    Args:
        s (str): string with non-ascii characters

    Returns:
        string of only the non-ascii characters

    Examples:
        >>> string_w_non_ascii_chars = 'Three fourths: ¾'
        >>> strip_non_ascii(string_w_non_ascii_chars)
        'Three fourths: '

    """
    return "".join(filter(lambda x: ord(x) <= 128, s))

fmts.striterable(string: str) -> Iterable[str] ⚓︎

Yield 'clean' sub-strings from an input string

This method takes a string (like the string that would be a dat file) and yields strings from that string separated by some delimiter.

Delimiters
  • (unix AND dos!)

Parameters:

Name Type Description Default
string str

string to be turned into a striterable

required

Returns:

Type Description
Iterable[str]

Filter/generator of 'clean' strings for comparison

Examples:

Simple spaces example:

>>> string_w_spaces = 'this is a string with spaces'
>>> list(striterable(string_w_spaces))
['this', 'is', 'a', 'string', 'with', 'spaces']

Leading and trailing spaces example:

>>> string_w_spaces = '     this is a string with spaces     '
>>> list(striterable(string_w_spaces))
['this', 'is', 'a', 'string', 'with', 'spaces']

Tabs example:

>>> strings = ['string', 'separated', 'by', 'tabs']
>>> tab_separated = '\t'.join(strings)
>>> list(striterable(tab_separated))
['string', 'separated', 'by', 'tabs']
Source code in libs/fmts/fmts/__init__.py
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
def striterable(string: str) -> Iterable[str]:
    r"""Yield 'clean' sub-strings from an input string

    This method takes a string (like the string that would be a dat file) and
    yields strings from that string separated by some delimiter.

    Delimiters:
        - <space>
        - <tab>
        - <new-line> (unix AND dos!)

    Args:
        string (str): string to be turned into a striterable

    Returns:
        Filter/generator of 'clean' strings for comparison

    Examples:
        Simple spaces example:

        >>> string_w_spaces = 'this is a string with spaces'
        >>> list(striterable(string_w_spaces))
        ['this', 'is', 'a', 'string', 'with', 'spaces']

        Leading and trailing spaces example:

        >>> string_w_spaces = '     this is a string with spaces     '
        >>> list(striterable(string_w_spaces))
        ['this', 'is', 'a', 'string', 'with', 'spaces']

        Tabs example:

        >>> strings = ['string', 'separated', 'by', 'tabs']
        >>> tab_separated = '\t'.join(strings)
        >>> list(striterable(tab_separated))
        ['string', 'separated', 'by', 'tabs']

    """
    string = string.replace("\r\n", " ")  # handle DOS line endings
    string = string.replace("\n", " ")
    string = string.replace("\t", " ")
    return (s.lower() for s in filter(lambda s: s != "", string.split(" ")))

fmts.t9(string: str) -> int ⚓︎

Convert a string to a number using ye olde T9

Parameters:

Name Type Description Default
string str

String to convert to T9 integer

required

Returns:

Name Type Description
int int

T9 integer

Examples:

>>> t9("Hello World")
43556096753
>>> t9("dgpy")
3479
Source code in libs/fmts/fmts/__init__.py
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
@anystr
def t9(string: str) -> int:
    """Convert a string to a number using ye olde T9

    Args:
        string (str): String to convert to T9 integer

    Returns:
        int: T9 integer

    Examples:
        >>> t9("Hello World")
        43556096753
        >>> t9("dgpy")
        3479

    """
    return int(t9_str(string))

fmts.t9_str(string: str) -> str ⚓︎

Convert a string to a number using ye olde T9

Parameters:

Name Type Description Default
string str

String to convert to T9 integer

required

Returns:

Name Type Description
str str

T9 integer as a string

Examples:

>>> t9_str("Hello World")
'43556096753'
>>> t9_str("dgpy")
'3479'
Source code in libs/fmts/fmts/__init__.py
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
@anystr
def t9_str(string: str) -> str:
    """Convert a string to a number using ye olde T9

    Args:
        string (str): String to convert to T9 integer

    Returns:
        str: T9 integer as a string

    Examples:
        >>> t9_str("Hello World")
        '43556096753'
        >>> t9_str("dgpy")
        '3479'

    """
    return string.translate(t9_translation())

fmts.timestamp(ts: Optional[Union[float, datetime]] = None) -> str ⚓︎

Time stamp string w/ format yyyymmdd-HHMMSS

Parameters:

Name Type Description Default
ts Optional[Union[float, datetime]]

datetime or float

None

Returns:

Type Description
str

timestamp string

Examples:

>>> from datetime import datetime
>>> stamps = ['20190225-161151', '20190225-081151']
>>> timestamp(1551111111.111111) in stamps
True
>>> datetime.now().strftime("%Y%m%d-%H%M%S") == timestamp()
True
>>> timestamp(datetime.now()) == timestamp()
True
Source code in libs/fmts/fmts/__init__.py
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
def timestamp(ts: Optional[Union[float, datetime]] = None) -> str:
    """Time stamp string w/ format yyyymmdd-HHMMSS

    Args:
        ts: datetime or float

    Returns:
        timestamp string

    Examples:
        >>> from datetime import datetime
        >>> stamps = ['20190225-161151', '20190225-081151']
        >>> timestamp(1551111111.111111) in stamps
        True
        >>> datetime.now().strftime("%Y%m%d-%H%M%S") == timestamp()
        True
        >>> timestamp(datetime.now()) == timestamp()
        True

    """
    if isinstance(ts, float):
        return datetime.fromtimestamp(ts).strftime("%Y%m%d-%H%M%S")
    if isinstance(ts, datetime):
        return ts.strftime("%Y%m%d-%H%M%S")
    return datetime.now().strftime("%Y%m%d-%H%M%S")

fmts.truncate_string(string: str, maxlines: int = 120, max_characters: int = 4096) -> str ⚓︎

Truncate a string at either a max number of lines or characters

Parameters:

Name Type Description Default
string str

String to truncate

required
maxlines int

Max number of lines the truncated string can have; default is 120

120
max_characters int

Max number of characters the string can have; default is 4096

4096

Returns:

Type Description
str

Truncated string

Examples:

>>> truncate_string('a')
'a'
>>> print(truncate_string('a\n' * 10, maxlines=5))
a
a
a
a
a
---------------------------
... Truncated @ 5 lines...
---------------------------
Source code in libs/fmts/fmts/__init__.py
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def truncate_string(
    string: str, maxlines: int = 120, max_characters: int = 4096
) -> str:
    r"""Truncate a string at either a max number of lines or characters

    Args:
        string: String to truncate
        maxlines: Max number of lines the truncated string can have; default is 120
        max_characters: Max number of characters the string can have; default is 4096

    Returns:
        Truncated string

    Examples:
        >>> truncate_string('a')
        'a'
        >>> print(truncate_string('a\n' * 10, maxlines=5))
        a
        a
        a
        a
        a
        ---------------------------
        ... Truncated @ 5 lines...
        ---------------------------


    """
    string_lines = string.replace("\r\n", "\n").split("\n")
    if len(string_lines) > maxlines:
        string_lines = string_lines[:maxlines]
        line_lengths = [len(line) for line in string_lines]
        total_characters = sum(line_lengths)
        if total_characters < max_characters:
            trunc_msg = f"... Truncated @ {maxlines} lines... "
            string_lines.extend(
                [
                    "-" * len(trunc_msg),
                    trunc_msg,
                    "-" * len(trunc_msg),
                ]
            )
            truncated_string = "\n".join(string_lines)
        else:
            truncated_string = "\n".join(string_lines)[:4096]
            trunc_msg = f"... Truncated @ {max_characters} characters ..."
            truncated_string += "\n".join(
                [
                    "-" * len(trunc_msg),
                    truncated_string,
                    "-" * len(trunc_msg),
                ]
            )
    else:
        truncated_string = "\n".join(string_lines)

    while "\n\n" in truncated_string:
        truncated_string = truncated_string.replace("\n\n", "\n")
    return truncated_string

fmts.udiff(a_lines: Sequence[str], b_lines: Sequence[str], fromfile: str = 'A', tofile: str = 'B', n: int = 0, maxlines: int = 120, max_characters: int = 4096) -> str ⚓︎

Return universal-diff as a string

Parameters:

Name Type Description Default
a_lines Sequence[str]

First set of lines as strings

required
b_lines Sequence[str]

Second set of lines as strings

required
fromfile str

Name or label of the first file/lines (Default = 'A')

'A'
tofile str

Name or label of the second file/lines (Default = 'B')

'B'
n int

Number of context lines to give in diff (Default = 0)

0
maxlines int

Number of diff lines to truncate at (Default = 120)

120
max_characters int

Number of characters to truncate at (Default = 4096)

4096

Returns:

Type Description
str

universal diff string that is truncated if too long

Source code in libs/fmts/fmts/__init__.py
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
def udiff(
    a_lines: Sequence[str],
    b_lines: Sequence[str],
    fromfile: str = "A",
    tofile: str = "B",
    n: int = 0,
    maxlines: int = 120,
    max_characters: int = 4096,
) -> str:
    """Return universal-diff as a string

    Args:
        a_lines: First set of lines as strings
        b_lines: Second set of lines as strings
        fromfile: Name or label of the first file/lines (Default = 'A')
        tofile: Name or label of the second file/lines (Default = 'B')
        n: Number of context lines to give in diff (Default = 0)
        maxlines: Number of diff lines to truncate at (Default = 120)
        max_characters: Number of characters to truncate at (Default = 4096)

    Returns:
        universal diff string that is truncated if too long

    """
    diff_string = "\n".join(
        filter(
            lambda string: string != "",
            unified_diff(
                a=a_lines,
                b=b_lines,
                fromfile=fromfile,
                tofile=tofile,
                n=n,  # number of context lines
            ),
        )
    )
    if maxlines <= 0 and max_characters <= 0:
        return diff_string
    return truncate_string(
        diff_string, maxlines=maxlines, max_characters=max_characters
    )

Modules⚓︎

fmts.__about__ ⚓︎

Package metadata/info

fmts.__main__ ⚓︎

pkg entry ~ python -m fmts

Functions⚓︎
fmts.__main__.main() -> None ⚓︎

Print package metadata

Source code in libs/fmts/fmts/__main__.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def main() -> None:
    """Print package metadata"""
    import json

    sys.stdout.write(
        json.dumps(
            {
                "package": __title__,
                "version": __version__,
                "pkgroot": __pkgroot__,
            },
            indent=2,
        )
    )