Skip to content

Commit e4c2489

Browse files
committed
feat(shorten): add middle argument
1 parent 6f92469 commit e4c2489

1 file changed

Lines changed: 25 additions & 5 deletions

File tree

‎shorten.py‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,23 @@
44
__author__ = "ipetrash"
55

66

7-
def shorten(text: str, length: int = 30, placeholder: str = "...") -> str:
8-
if not text:
7+
def shorten(
8+
text: str,
9+
length: int = 30,
10+
middle: bool = False,
11+
placeholder: str = "...",
12+
) -> str:
13+
if not text or len(text) <= length:
914
return text
1015

11-
if len(text) > length:
12-
text = text[: length - len(placeholder)] + placeholder
13-
return text
16+
if middle:
17+
available_len: int = length - len(placeholder)
18+
start_len: int = available_len // 2
19+
end_len: int = available_len - start_len
20+
21+
return text[:start_len] + placeholder + text[-end_len:]
22+
23+
return text[: length - len(placeholder)] + placeholder
1424

1525

1626
if __name__ == "__main__":
@@ -33,3 +43,13 @@ def shorten(text: str, length: int = 30, placeholder: str = "...") -> str:
3343
text = "12356"
3444
new_text = shorten(text, length=3)
3545
assert new_text == "..."
46+
47+
file_name: str = r"C:\Users\ipetrash\PycharmProjects\SimplePyScripts\_FOO_TEST_TEST\FOO_TEST_TEST.py"
48+
49+
short_file_name: str = shorten(file_name)
50+
assert len(short_file_name) == 30
51+
assert short_file_name == r"C:\Users\ipetrash\PycharmPr..."
52+
53+
short_file_name: str = shorten(file_name, middle=True)
54+
assert len(short_file_name) == 30
55+
assert short_file_name == r"C:\Users\ipet...O_TEST_TEST.py"

0 commit comments

Comments
 (0)