-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathformatting.py
36 lines (29 loc) · 1014 Bytes
/
formatting.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
import re
class Formatter(object):
latex_substitutions = {
re.compile("\["): "{[}",
re.compile("\]"): "{]}",
re.compile("<"): r"\\textless",
re.compile(">"): r"\\textgreater"
}
def __init__(self, decimals=4):
self.set_decimals(decimals)
def set_decimals(self, decimals):
self.decimals = decimals
def escape_latex(self, x):
"""Adds escape sequences wherever needed to make the output
LateX compatible"""
for pat, replace_with in self.latex_substitutions.items():
x = pat.sub(replace_with, x)
return x
def __call__(self, x, latex=True):
"""Convert object to string with controlled decimals"""
if isinstance(x, str):
return self.escape_latex(x) if latex else x
elif isinstance(x, int):
return f"{x:d}"
elif isinstance(x, float):
return f"{x:.{self.decimals}f}"
else:
str(x)
fmt = Formatter(decimals=4)