Repository navigation
Expand file tree
/
Copy pathch03_ex2.py
More file actions
61 lines (50 loc) · 1.38 KB
/
Copy pathch03_ex2.py
File metadata and controls
61 lines (50 loc) · 1.38 KB
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
#!/usr/bin/env python3
"""Functional Python Programming
Chapter 3, Example Set 2
"""
from decimal import *
def clean_decimal_1(text):
"""
Remove $ and , from a string, return a Decimal.
>>> clean_decimal_1( "$1,234.56" )
Decimal('1234.56')
"""
if text is None: return text
try:
return Decimal(text.replace("$","").replace(",",""))
except InvalidOperation:
return text
def replace(str, a, b):
"""Prefix function for str.replace(a,b)."""
return str.replace(a,b)
def clean_decimal_2(text):
"""
Remove $ and , from a string, return a Decimal.
>>> clean_decimal_2( "$1,234.56" )
Decimal('1234.56')
"""
if text is None: return text
try:
return Decimal(replace(replace(text, "$", ""), ",", ""))
except InvalidOperation:
return text
def remove( str, chars ):
"""Remove all of the given chars from a string."""
if chars: return remove( str.replace(chars[0], ""), chars[1:] )
return str
def clean_decimal_3(text):
"""
Remove $ and , from a string, return a Decimal.
>>> clean_decimal_3( "$1,234.56" )
Decimal('1234.56')
"""
if text is None: return text
try:
return Decimal(remove( text, "$,") )
except InvalidOperation:
return text
def test():
import doctest
doctest.testmod(verbose=2)
if __name__ == "__main__":
test()