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...
CodePudding user response:
Use f-strings
:
s1 = 'apple'
s2 = 'banana'
X = 10
s = f"{s1}{' ' * X}{s2}"
print(s)
# Output
'apple banana'
CodePudding user response:
Try this code
string1 = 'apple'
string2 = 'banana'
X = 10
string3 = string1 ' '*X string2
print(string3)
Output:
apple banana
CodePudding user response:
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))
CodePudding user response:
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