How can I make the word not break in half? And leave at most 40 characters per line?

Asked

Viewed 53 times

5

valor = '''In the beginning God created the heavens and the earth. Now the 
earth was formless and empty, darkness was over the surface of the deep, and 
the Spirit of God was hovering over the waters.
And God said, "Let there be light," and there was light. God saw that the light 
was good, and he separated the light from the darkness. God called the light 
"day," and the darkness he called "night." And there was evening, and there was 
morning - the first day.'''

lista = valor
i = 0
f = 40
for c in lista:
    print(lista[i:f])
    i += 40
    f += 40
  • What was your goal to go through all the characters of the text with this for?

  • Well, I used it to put up to 40 characters per line.

1 answer

8


Use the module textwrap that comes in python:

import textwrap
for linha in textwrap.wrap(valor, 40):
    print(linha)

Upshot:

In the beginning God created the heavens
and the earth. Now the  earth was
formless and empty, darkness was over
the surface of the deep, and  the Spirit
of God was hovering over the waters. And
God said, "Let there be light," and
there was light. God saw that the light
was good, and he separated the light
from the darkness. God called the light
"day," and the darkness he called
"night." And there was evening, and
there was  morning - the first day.
  • Good. I was already warming my fingers here to re-invent the wheel. : -D . I use a lot the textwrap.dedent, however.

  • And there is some way to justify the text with textwrap?

  • 1

    No, the module does not work with @Nathaliadias justification but it can be extended. If you need to justify I suggest opening a new question

Browser other questions tagged

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