Source code

Download source archive ↓

src/openpyxl/utils/escape.py

1# Copyright (c) 2010-2024 openpyxl
2
3"""
4OOXML has non-standard escaping for characters < \031
5"""
6
7import re
8
9
10def escape(value):
11    r"""
12    Convert ASCII < 31 to OOXML: \n == _x + hex(ord(\n)) + _
13    """
14
15    CHAR_REGEX = re.compile(r"[\001-\031]")
16
17    def _sub(match):
18        """
19        Callback to escape chars
20        """
21        return "_x{:0>4x}_".format(ord(match.group(0)))
22
23    return CHAR_REGEX.sub(_sub, value)
24
25
26def unescape(value):
27    r"""
28    Convert escaped strings to ASCIII: _x000a_ == \n
29    """
30
31
32    ESCAPED_REGEX = re.compile("_x([0-9A-Fa-f]{4})_")
33
34    def _sub(match):
35        """
36        Callback to unescape chars
37        """
38        return chr(int(match.group(1), 16))
39
40    if "_x" in value:
41        value = ESCAPED_REGEX.sub(_sub, value)
42
43    return value