Adding spaces between words evenly from left to right untill a certain length

Question:

Receiving a string that has 2 or more words and a certain length, I need to insert spaces uniformly between words, adding additional spaces between words from left to right. Let’s say I receive "Hello I’m John" and a length of 17, it should return:'Hello I'm John

I have tried many different ways and I couldn’t do the left-to-right requirement.

This is what I have now:

 if ' ' in string:
        final_string=''
        string=string.split()
        for i in range(len(string)):
            if string[i]==string[-1]:
                final_string+=string[i]
            else:
                final_string+=string[i]+'  '
print(final_string)

Output:
Hello I'm John

which gives me a length greater than what I want…

Asked By: 03Sparta

||

Answers:

Probably something like this?

words = cad_carateres.split()
total_nb_of_spaces_to_add = total_string_length - len(cad_carateres)

nb_of_spaces_to_add_list = [total_nb_of_spaces_to_add // (len(words) - 1) 
+ int(i < (total_nb_of_spaces_to_add % (len(words) - 1))) 
                   for i in range(len(words) - 1)]  + [0]

result = ' '.join([w + ' ' * (nb_of_spaces_to_add) 
             for w, nb_of_spaces_to_add in zip(words, nb_of_spaces_to_add_list)])

First line – you split your line into words

Second line – how many spaces, in total, we need to add.

Third line – suppose that we need to add 20 spaces, and we have 7 words in total (thus, 6 gaps where we add additional spaces). Let’s add [3, 3, 2, 2, 2, 2] spaces in these gaps, and, obviously 0 spaces after the last word. nb_of_spaces_to_add_list will contain the list like [3, 3, 2, 2, 2, 2, 0]

The last line line – join the padded (with spaces, their number comes from nb_of_spaces_to_add_list) words into the string – this is your result! I also use zip function to convert 2 one-dimensional lists (words and number of spaces to add) into a two-dimensional list, this allows me to use list comprehension.

Answered By: Yulia V

Are you looking like something like this?

def main():
    sentence="Hello my name is John"
    words=sentence.split()
    new_sentence="  ".join(words)
    print(new_sentence)
main()
Answered By: stabakunin
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.