Is it possible to write all the paragraphs that the user only put after the loop in sequence? and in a justified way?

Asked

Viewed 51 times

0

Is it possible to write all paragraphs that the user has put only after the loop in sequence? and in a justified way?

import textwrap

numero_paragrafos = int(input('Quantos parágrafos tem o texto?\n'))

for c in range(1, numero_paragrafos +1):
    paragrafo = str(input(f'\n parágrafo {c}: \n'))
    print(textwrap.fill(paragrafo, width=40))

1 answer

1


You asked two questions in one.

You can write all the paragraphs that the user put only after the loop in sequence?

From what I understand, you only want to write after the loop is finished, so you need to use a variable to store the result:

paragrafos = [] # lista para armazenar os paragrafos lidos
for c in range(1, numero_paragrafos +1):
    paragrafo = str(input(f'\n parágrafo {c}: \n'))
    paragrafos.append(paragrafo)

# apos ler todos os paragrafos, imprima o resultado
for paragrafo in paragrafos:
    print(textwrap.fill(paragrafo, width=40))

and in a justified manner?

You can use this function justifica, it works like the textwrap.wrap() but justifies the text:

def justifica(texto, tamanho):
    for linha in textwrap.wrap(texto.replace('\n', ''), tamanho):
        por_palavra, sobra = divmod(tamanho - len(linha), linha.count(' '))
        por_palavra *= ' '; sobra *= [' ']
        yield ' '.join(palavra + por_palavra + (sobra.pop() if sobra else '') 
            for palavra in linha.split(' ')).rstrip()

The way it works is by calling the textwrap.wrap() and then completing each row with distributed spaces until it gets the requested size:

To use in your code, just put it print line:

print('\n'.join(justifica(paragrafo, 40)))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.