Skip to content

Instantly share code, notes, and snippets.

@jiunbae
Created December 8, 2021 04:08
Show Gist options
  • Save jiunbae/d589b26e3a26724c174f8357cecbada4 to your computer and use it in GitHub Desktop.
Save jiunbae/d589b26e3a26724c174f8357cecbada4 to your computer and use it in GitHub Desktop.
def truncate(string: str, max_length: int, suffix: str = "...", include_suffix_length: bool = True, mode: str = "center"):
"""Truncate string
:param string: input string
:param include_suffix_length: include suffix length to max_length
:param max_length: if string length is bigger than max_length, than truncate
:param suffix: trucate string, replace remain string to suffix
:param mode: select in ['left', 'center', 'right']
"""
if include_suffix_length:
max_length -= len(suffix)
if (str_length := len(string)) > max_length:
diff = str_length - max_length
if mode == "left":
begin, end = 0, diff
elif mode == "center":
begin = str_length // 2 - (diff // 2)
end = str_length // 2 - (-diff // 2)
elif mode == "right":
begin, end = max_length, str_length
else:
raise NotImplementedError(f"{mode} is not implemented, use 'left', 'center' and 'right'")
string = string[:begin] + suffix + string[end:]
return string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment