Search code examples
pythonstringletter

How to add new line after number of word


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)

Solution

  • 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 '