Home > Back-end >  How to pad given number of spaces between words in a string?
How to pad given number of spaces between words in a string?

Time:11-17

Details:

  1. Given a string s that contains words. I am also given spaces which specifies the number of extra spaces to add between words.

  2. The number of spots will be len(words)-1.

  3. If spaces/spots is an odd number then the left slot gets more spaces.

Example1:

s = "This is an"
spaces = 6
Ans = "This    is    an"  
#Explanation - 3 spaces added after "this" and 3 spaces added after "is"

Example2:

s = "This is an"
spaces = 7
Ans = "This     is    an"  
#Explanation - 4 spaces added after "this" and 3 spaces added after "is"

Solution:

def solution(s, spaces):
    spots = len(s.split())-1
    space_for_every_spot = spaces/spots
    ...

CodePudding user response:

The solution would be splitting your string, then based on some simple divisions calculate the amount of extra spaces. I can propose the following solution:

def solution(s, spaces):
    words = s.split(" ")
    spots = len(words) - 1
    n_spaces = spaces // spots
    n_extra_spaces = spaces - n_spaces * spots
    result = words[0]   " " * (n_spaces   n_extra_spaces)
    for word in words[1:]:
        result  = word   " " * n_spaces
    return result

CodePudding user response:

Calculate the number of spaces needed between the words and the remainder, split the words, join with the even spacing, then replace the first words spaces from the left with the larger amount.

s = 'The quick brown fox jumped over the lazy dog.'
spaces = 20

words = s.split()
space_count, extra_count = divmod(spaces, len(w) - 1)
spacing = ' ' * space_count
extra_spacing = ' ' * (space_count   1)
result = spacing.join(words)
result = result.replace(spacing, extra_spacing, extra_count)
print(result)
print(result.replace(' ', '.'))  # for easier counting

Output:

The   quick   brown   fox   jumped  over  the  lazy  dog.
The...quick...brown...fox...jumped..over..the..lazy..dog.
  • Related