-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathfstr.py
61 lines (54 loc) · 1.28 KB
/
fstr.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
52
53
54
55
56
57
58
59
60
61
from inspect import currentframe
def f(s):
"""
Mimic the functionality of formatted strings in Python3. Convert curly brackets in s
to expressions.
>>> f('3+2={3+2}.')
'3+2=5.'
>>> f('3+2={3+2}')
'3+2=5'
>>> f('{"="*3} test {"="*3}')
'=== test ==='
>>> f('{{hello}}')
'{hello}'
>>> metric="gxx"
>>> f('\\texttt{{{metric}}}')
'\\texttt{gxx}'
"""
globs = currentframe().f_back.f_globals
locs = currentframe().f_back.f_locals
count = 0
ns = u''
i = 0
while i < len(s):
c = s[i]
if i + 1 < len(s):
nc = s[i + 1]
else:
nc = ""
i += 1
if c == '{' and nc == '{':
ns += '{'
i += 1
elif c == '}' and nc == '}':
ns += '}'
i += 1
elif c == '{':
count = 1
j = i
while i < len(s):
if s[i] == '{':
count += 1
elif s[i] == '}':
count -= 1
if count == 0:
break
i += 1
ns += str(eval(s[j:i], globs, locs))
i += 1
else:
ns += c
return ns
if __name__ == "__main__":
import doctest
doctest.testmod()