-
Notifications
You must be signed in to change notification settings - Fork 1
/
formatist.py
52 lines (45 loc) · 1.53 KB
/
formatist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
A Python library to convert from older `%` style format strings, to newer
`{}` style.
"""
import re
__all__ = [
'convert',
]
def convert(fmtstr):
"""Convert %-style format specifiers in `fmtstr` to {}-style specifiers
>>> convert("Hello %(name)s. It's %(temp).1f C")
"Hello {name!s:}. It's {temp:>.1f} C"
"""
oldFormatString = fmtstr
matches = re.finditer(r"(%)(\((?P<name>.*?)\))"
r"(?P<flags>[ #0\-\+])?"
r"(?P<minimum>(\*|\d*))"
r"(?P<precision>\.(\*|\d*))?"
r"(?P<conversion>[diouxXeEfFgGcrs%])",
oldFormatString)
result = []
previousEnd = 0
for match in matches:
result.append(oldFormatString[previousEnd:match.start()])
conv = match.group("conversion")
if conv in 'sr':
bang = "!" + conv
colon = ":"
else:
bang = ""
fill = match.group("flags") or ""
align = ">"
sign = ""
sharp = ""
zero = ""
width = match.group("minimum") or ""
comma = ""
precision = match.group("precision") or ""
ctype = conv
colon = ":" + (fill + align + sign + sharp + zero + width + comma +
precision + ctype)
result.append("{" + match.group("name") + bang + colon + "}")
previousEnd = match.end()
result.append(oldFormatString[previousEnd:])
return ''.join(result)