Skip to content

Instantly share code, notes, and snippets.

@renzon
Created June 6, 2017 17:41
Show Gist options
  • Save renzon/cff2cdcfc16a24306b1956a4a54b598d to your computer and use it in GitHub Desktop.
Save renzon/cff2cdcfc16a24306b1956a4a54b598d to your computer and use it in GitHub Desktop.
def truncar(texto:str, largura:'int > 0'=80) -> str:
'''devolve o texto truncado no primeiro espaço até a largura,
ou no primeiro espaço após a largura, se existir
'''
termino = None
if len(texto) > largura:
pos_espaco_antes = texto.rfind(' ', 0, largura)
if pos_espaco_antes >= 0:
termino = pos_espaco_antes
else:
pos_espaco_depois = texto.rfind(' ', largura)
if pos_espaco_depois >= 0:
termino = pos_espaco_depois if termino is None:
return texto.rstrip() else:
return texto[:termino].rstrip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment