Skip to content

Instantly share code, notes, and snippets.

@biazzotto
Last active June 3, 2020 15:38
Show Gist options
  • Save biazzotto/77993bc8d48c6f4fe17ab79ac5a99b07 to your computer and use it in GitHub Desktop.
Save biazzotto/77993bc8d48c6f4fe17ab79ac5a99b07 to your computer and use it in GitHub Desktop.
Função que retorna strings alinhadas dentro de uma string com um tamanho determinado (80 caracteres por padrão), usando um caractere de preenchimento (espaço em branco por padrão). Caso nenhuma string seja fornecida, retorna uma string preenchida com o tamanho e o caractere de preenchimento fornecidos.
def pad_string(*args, lenght=80, char=chr(32)):
if len(char) == 0 or not isinstance(char, str):
char = chr(32)
else:
char = char[0]
if str(lenght).isdigit():
lenght = int(lenght) or 80
else:
lenght = 80
result = list(char * lenght)
for arg in args:
if not isinstance(arg, str):
arg = f'{arg}'
if len(arg) < 2:
arg = f'{arg:{char}<2}'
if arg[0] not in('<', '>', '^'):
arg = f'<{arg}'
if arg[0] == '<':
for i in range(1, len(arg)):
result[i - 1] = arg[i]
elif arg[0] == '^':
for i in range(1, len(arg)):
s = (lenght // 2) - (len(arg) // 2) - 1
result[s + i] = arg[i]
elif arg[0] == '>':
for i in range(1, len(arg)):
result[lenght - len(arg) + i] = arg[i]
return(''.join(result))
# Example of use
lenght = 150
print(pad_string(lenght=lenght, char='*'))
print(pad_string('<LEFT', '^CENTER', '>RIGHT', lenght=lenght, char=' '))
print(pad_string(lenght=lenght, char='*'))
print(pad_string('<1. Title ', '> 1', lenght=lenght, char='.'))
print(pad_string('<1.1 Subtitle ', '> 2', lenght=lenght, char='.'))
print(pad_string(lenght=lenght, char='*'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment