Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add line break after every 20 characters and save result as a new string [duplicate]

Tags:

python

I have a string variable input = "A very very long string from user input", how can I loop through the string and add a line break \n after 20 characters then save the formatted string in a variable new_input?

So far am only able to get the first 20 characters as such input[0:20] but how do you do this through the entire string and add line breaks at that point?

like image 616
Johnn Kaita Avatar asked Dec 02 '22 09:12

Johnn Kaita


1 Answers

You probably want to do something like this

inp = "A very very long string from user input"
new_input = ""
for i, letter in enumerate(inp):
    if i % 20 == 0:
        new_input += '\n'
    new_input += letter

# this is just because at the beginning too a `\n` character gets added
new_input = new_input[1:] 
like image 137
IsharM Avatar answered May 19 '23 08:05

IsharM