Created
February 8, 2020 04:01
-
-
Save luisenriquecorona/71e9127111af27f7ffd4e4515d148499 to your computer and use it in GitHub Desktop.
Function to shorten a string by clipping at a space near the desired length.
This file contains hidden or 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 clip(text, max_len=80): | |
"""Return text clipped at the last space before or after max_len | |
""" | |
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: # no spaces were found | |
end = len(text) | |
return text[:end].rstrip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment