I am looking for a way to add spaces between words in a string until len(string) < n is reached. I've tried this:
string = "you are great"
n = 20
res = []
for i in string:
if ord(i) == 32 and len(string) < num:
res = [string i]
And I want it to add spaces between "you" and "are", and "are" and "great. So it gives me something like this:
res = ["you are great"]
But instead I get this
"you are great "
CodePudding user response:
No need of loops:
string = "you are great"
n = 20
a = n - len(string.replace(' ', '')) # amount of spaces to add
b = string.split() # list of words (without spaces)
if a & 1:
b[0] = ' ' # if 'a' is odd, add an extra space to first word
d = (' ' * (a // 2)).join(b) # concatenate all words with 'a' spaces between them
print(d)
The output is:
"you are great"
CodePudding user response:
You code is doing what it is suppose to do but as you can see in the second output it adds a space to your string. The code below is the issue.
Res = [string i]