forked from tuvo1106/python_design_patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext_formatting.py
More file actions
58 lines (47 loc) · 1.54 KB
/
text_formatting.py
File metadata and controls
58 lines (47 loc) · 1.54 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
class FormattedText:
def __init__(self, plain_text):
self.plain_text = plain_text
self.caps = [False] * len(plain_text)
def capitalize(self, start, end):
for i in range(start, end):
self.caps[i] = True
def __str__(self):
result = []
for i in range(len(self.plain_text)):
c = self.plain_text[i]
result.append(
c.upper() if self.caps[i] else c
)
return ''.join(result)
class BetterFormattedText:
def __init__(self, plain_text):
self.plain_text = plain_text
self.formatting = []
class TextRange:
def __init__(self, start, end, capitalize=False):
self.start = start
self.end = end
self.capitalize = capitalize
def covers(self, position):
return self.start <= position <= self.end
def get_range(self, start, end):
range = self.TextRange(start, end)
self.formatting.append(range)
return range
def __str__(self):
result = []
for i in range(len(self.plain_text)):
c = self.plain_text[i]
for r in self.formatting:
if r.covers(i) and r.capitalize:
c = c.upper()
result.append(c)
return ''.join(result)
if __name__ == "__main__":
TEXT = "This is a brave new world"
FT = FormattedText(TEXT)
FT.capitalize(10, 15)
print(FT)
BFT = BetterFormattedText(TEXT)
BFT.get_range(16, 19).capitalize = True
print(BFT)