-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat_text.py
120 lines (83 loc) · 3.23 KB
/
format_text.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# format_text.py
def center_text(text, width=80, cap='#', fill='=', inner_cap='', out='print'):
"""Make a title centered inside filler characters
Arguments:
text String, this appears in the center
width Integer, number of characters wide
cap String, this appears as the "bookends" at either end of
the output line. Here are some values:
' '
'#'
'+'
'//'
'/*' NOTE: If you use this, it will be reversed on the
right cap such that it closes the comment.
fill String, this appears repeatedly to create the visual
demarcation. Here are some values:
' '
'='
'-'
'#'
inner_cap String, this appears just inside the cap and just outside
of the fill. Here are some values:
'' Empty string, no inner_cap
' '
' ' Three spaces
out String, either 'print' or 'return'. How would you like
the output delivered?
"""
len_text = len(text)
len_cap = len(cap)
len_inner_cap = len(inner_cap)
len_fill = width - (2 * (len_cap + len_inner_cap) + 2) - len_text
if len_fill < 0:
raise Exception("The input text is too wide for the width, cap, and "
"inner_cap that you have chosen. len_fill = %s." %
len_fill)
len_fill_left = len_fill // 2
len_fill_right = len_fill_left + (len_fill % 2)
fill_left = make_fill(fill, len_fill_left)
fill_right = make_fill(fill, len_fill_right)
output = [
cap,
inner_cap,
fill_left,
' ',
text,
' ',
fill_right,
inner_cap,
]
if cap == '/*':
output.append('*/')
else:
output.append(cap)
output_str = ''.join(output)
if out == 'print':
print output_str
else:
return output_str
def make_fill(fill, length):
"""Repeat 'fill' as many times as necessary, then trim to 'length'
Arguments:
fill String, e.g. '=', '-', '- ', '*'
length Integer, the length of the desired output string
"""
num_repeats = length // len(fill)
remainder = length % len(fill)
if remainder:
num_repeats += 1
output = fill * num_repeats
return output[:length]
def d(text, width=80, cap='#', fill='=', inner_cap='', out='print'):
"""Double-line, looks like this:
#================================ Text ================================#
"""
return center_text(text, width, cap, fill, inner_cap, out)
def s(text, width=80, cap='#', fill='-', inner_cap='', out='print'):
"""Single-line, looks like this:
#-------------------------------- Text --------------------------------#
"""
return center_text(text, width, cap, fill, inner_cap, out)
def help():
print center_text.__doc__