Created
May 6, 2022 14:28
-
-
Save brunomsantiago/2773c3cdad7f07b6d73409537434d53f to your computer and use it in GitHub Desktop.
Shortening strings in python (inspired by standard library textwrap.shorten)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def shorten_end(string, width=80, placeholder=' ...'): | |
if len(string) <= width: | |
return string | |
n2 = width - len(placeholder) | |
return string[:n2] + placeholder | |
def shorten_begin(string, width=80, placeholder='... '): | |
if len(string) <= width: | |
return string | |
n1 = len(string) - width + len(placeholder) | |
return placeholder + string[n1:] | |
def shorten_middle(string, width=80, placeholder=' ... '): | |
if len(string) <= width: | |
return string | |
n2 = int( (width - len(placeholder)) / 2 ) | |
m1 = - (width - n2 - len(placeholder)) | |
return string[:n2] + placeholder + string[m1:] | |
print(shorten_end('nineteen characters', 19)) | |
print(shorten_end('nineteen characters', 18)) | |
print(shorten_end('Much more than nineteen characters', 19)) | |
print('') | |
# Output: | |
# nineteen characters | |
# nineteen chara ... | |
# Much more than ... | |
print(shorten_begin('nineteen characters', 19)) | |
print(shorten_begin('nineteen characters', 18)) | |
print(shorten_begin('Much more than nineteen characters', 19)) | |
print('') | |
# Output: | |
# nineteen characters | |
# ... een characters | |
# ... teen characters | |
print(shorten_middle('nineteen characters', 19)) | |
print(shorten_middle('nineteen characters', 18)) | |
print(shorten_middle('Much more than nineteen characters', 19)) | |
# Output: | |
# nineteen characters | |
# ninete ... racters | |
# Much mo ... racters |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment