How to add new line after number of word

Question:

i find a code to seperate line, but it cut hafl of word "A very very long str" n "ing from user input". so i want to ask how to keep the original word. its mean add n after a number of word?

# 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:]
# print(new_input)
Asked By: Thịnh Phạm

||

Answers:

Using a simple loop on a list of the words:

inp = "A very very long string from user input"

start = 0
N = 3
l = inp.split()
for stop in range(N, len(l)+N, N):
    print(' '.join(l[start:stop]))
    start = stop

output:

A very very
long string from
user input
Answered By: mozway

Try using str.split() 1 and give it space as a delimiter:

words = inp.split(' ')

That should return a list of words

Answered By: andrew

I see that there is already an accepted answer, but I’m not sure that it completely answers the original question. The accepted answer will only split the string provided into lines with 3 words each. However, what I understand the question to be is for the string to be split into lines of a certain length (20 being the length provided). This function should work:

def split_str_into_lines(input_str: str, line_length: int):
    words = input_str.split(" ")
    line_count = 0
    split_input = ""
    for word in words:
        line_count += 1
        line_count += len(word)
        if line_count > line_length:
            split_input += "n"
            line_count = len(word) + 1
            split_input += word
            split_input += " "
        else:
            split_input += word
            split_input += " "
    
    return split_input
        
inp = "A very very long string from user input"
length = 20
new_input = split_str_into_lines(inp,length)
print(new_input)
new_input

Giving result:

"""
A very very long 
string from user 
input 
"""

or

'A very very long nstring from user ninput '
Answered By: dnelson17
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.