Skip to content

Commit ea48d42

Browse files
committed
Add function to truncate strings.
1 parent da211cf commit ea48d42

File tree

3 files changed

+40
-3
lines changed

3 files changed

+40
-3
lines changed

doc-source/api/words.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,9 @@ Functions
112112
.. autofunction:: domdf_python_tools.words.get_words_list
113113
.. autofunction:: domdf_python_tools.words.get_random_word
114114
.. autofunction:: domdf_python_tools.words.word_join
115-
116-
117115
.. latex:clearpage::
116+
.. autofunction:: domdf_python_tools.words.truncate_string
117+
118118

119119
Classes
120120
-------------

domdf_python_tools/words.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@
7676
"LF",
7777
"Plural",
7878
"PluralPhrase",
79+
"truncate_string",
7980
]
8081

8182
ascii_digits = "0123456789"
@@ -685,3 +686,30 @@ def __call__(self, n: int) -> str: # noqa: TYP004 # TODO
685686

686687
plural_words = [x(n) for x in self.words]
687688
return self.template.format(*plural_words, n=n)
689+
690+
691+
@functools.lru_cache()
692+
def _slice_end(max_length: int, ending: str = "...") -> slice:
693+
slice_end = max_length - len(ending)
694+
return slice(slice_end)
695+
696+
697+
def truncate_string(string: str, max_length: int, ending: str = "...") -> str:
698+
"""
699+
Truncate a string to ``max_length`` characters, and put ``ending`` on the end.
700+
701+
The truncated string is further truncated by the length of ``ending`` so the returned string is no more then ``max_length``.
702+
703+
.. versionadded:: 3.3.0
704+
705+
:param string:
706+
:param max_length:
707+
:param ending:
708+
"""
709+
710+
string_length = len(string)
711+
712+
if string_length > max_length:
713+
return string[_slice_end(max_length, ending)] + ending
714+
else:
715+
return string

tests/test_words.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
PluralPhrase,
1919
alpha_sort,
2020
get_random_word,
21-
get_words_list
21+
get_words_list,
22+
truncate_string
2223
)
2324

2425

@@ -208,3 +209,11 @@ def test_pluralphrase():
208209
assert repr(phrase3) == phrase3_repr
209210
phrase4_repr = "PluralPhrase(template='The farmer has {n} {0}. The {0} {1} brown.', words=(Plural('cow', 'cows'), Plural('is', 'are')))"
210211
assert repr(phrase4) == phrase4_repr
212+
213+
214+
def test_truncate():
215+
message = "hello world this is a very long sentance with no point"
216+
assert truncate_string(message, 20) == "hello world this ..."
217+
assert truncate_string(message, 30) == "hello world this is a very ..."
218+
assert truncate_string(message, 30, '…') == "hello world this is a very lo…"
219+
assert truncate_string(message, 200, '…') == message

0 commit comments

Comments
 (0)