Insert line break based on number of characters avoiding cutting words

Asked

Viewed 87 times

0

I’m starting in Python and I’m struggling with something relatively simple that I’m not able to accomplish, I’d like to add a line break in a string every 13 characters without cutting the words in half for example:

'gosto de comer abacate'

if I simply add the " n" every 13 characters the sentence will be cut next to the word resulting in:

'gosto de come
r abacate'

would like to know how to break the line without cutting the word something similar to:

'gosto de 
comer abacate'
  • 1

    Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.

1 answer

-1


As you said you are starting here I will do well didactic, but you can simplify my code much more (for example, starting the count at 0, as is the standard of most programming languages and counting up to 12).

In short what you should do is analyze each character by counting its position from 1 to 13. So if you get to 13 you must break the sentence by inserting the \n, however, only if the next character is a space, indicating that we are facing the end of a word.

exemplo = 'gosto de comer abacate pra caramba meu deus que bom o abacate'

limite = 13
atual = 1
novaString = ''

for x in exemplo:
    atual += 1
    if atual >= 13 and x == ' ':
        novaString = novaString + '\n' 
        atual = 1
    else:
        novaString = novaString + x    

print(novaString)

Exit:

gosto de comer  
abacate pra  
caramba meu 
deus que bom 
o abacate

Browser other questions tagged

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