-4

This may sound odd, but I want to be able to insert a varying certain number of spaces between two strings. So, in some cases it may be 10 spaces, in other cases 5 space or anything in that range, so that together the first string plus the empty spaces always adds up to the same length, for example let's say the total of the first string and spaces should be 20 characters altogether.

I have a way of knowing what that number of spaces is, so you can assume that X spaces is known. The question is how to write the code to insert that X number of spaces, between the two strings.

examples:

X = 5

Desired output:

apple     banana

X = 10

Desired output

 orange          strawberry

X = 14

desired output

car              machine

You get the idea... Shortcuts for adding up the first string with the empty spaces to equal 20 characters (for example) are also welcome...

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
A Feldman
  • 1
  • 2
  • What have you already tried? Did you get a specific error with your attempt? – DeepSpace Feb 20 '22 at 12:45
  • Please add your current progress(current code) to the question – Anshumaan Mishra Feb 20 '22 at 12:46
  • What is the input? Is it a single string like ``"apple banana"``, two strings like ``"apple", "banana"``, or something else? – MisterMiyagi Feb 20 '22 at 12:51
  • The situations of "first string plus the empty spaces always adds up to the same length" and "how to write the code to insert that X number of spaces" are two different questions. The answer for the latter is *not* optimal for the former! Which one are you actually interested in? – MisterMiyagi Feb 20 '22 at 12:52
  • Does this answer your question? [How can I fill out a Python string with spaces?](https://stackoverflow.com/questions/5676646/how-can-i-fill-out-a-python-string-with-spaces) – MisterMiyagi Feb 20 '22 at 12:56

4 Answers4

1

you can multiply string " " * X, then concatenate it together

def add_spaces(str1, str2, x):
    return str1+x*" "+str2


print(add_spaces('hello', 'world', 10))
Tomáš Šturm
  • 489
  • 4
  • 8
0

Use f-strings:

s1 = 'apple'
s2 = 'banana'
X = 10

s = f"{s1}{' ' * X}{s2}"
print(s)

# Output
'apple          banana'
Corralien
  • 109,409
  • 8
  • 28
  • 52
0

Try this code

string1 = 'apple'
string2 = 'banana'
X = 10
string3 = string1 + ' '*X +string2
print(string3)

Output:

apple          banana
Manjunath K Mayya
  • 1,078
  • 1
  • 11
  • 20
-1

You can get the final string directly using the rjust method on the second word:

left   = "apple"
right  = "banana"
total  = 20

joined = left + right.rjust(total-len(left))

print(joined)

apple         banana
Alain T.
  • 40,517
  • 4
  • 31
  • 51