forked from fluentpython/example-code-2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clip_annot.py
38 lines (36 loc) · 945 Bytes
/
clip_annot.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
"""
>>> clip('banana ', 6)
'banana'
>>> clip('banana ', 7)
'banana'
>>> clip('banana ', 5)
'banana'
>>> clip('banana split', 6)
'banana'
>>> clip('banana split', 7)
'banana'
>>> clip('banana split', 10)
'banana'
>>> clip('banana split', 11)
'banana'
>>> clip('banana split', 12)
'banana split'
"""
# tag::CLIP_ANNOT[]
def clip(text: str, max_len: int = 80) -> str:
"""Return new ``str`` clipped at last space before or after ``max_len``.
Return full ``text`` if no space found.
"""
end = None
if len(text) > max_len:
space_before = text.rfind(' ', 0, max_len)
if space_before >= 0:
end = space_before
else:
space_after = text.rfind(' ', max_len)
if space_after >= 0:
end = space_after
if end is None:
end = len(text)
return text[:end].rstrip()
# end::CLIP_ANNOT[]