I'm having a tough time finding the exact wording for my question since I'm new to formatting strings.

Let's say I have two variables:

customer = 'John Doe'balance = 39.99

I want to print a line that 25 characters wide, and fills the space between the two values with a specific character (in this case, periods):

'John Doe .......... 39.99'

So as I loop through customers, I want to print a line that is always 25 characters, with their name at the left, and their balance at the right, and allow the periods to adjust to fill the space between.

I can break this into multiple steps and accomplish the result...

customer = 'Barry Allen'balance = 99spaces = 23 - len(customer + str(balance))'{} {} {}'.format(customer, '.' * spaces, balance)# of course, this assumes that len(customer + str(balance)) is less than 23 (which is easy to work around)

...but I'm curious if there is a more "elegant" way of doing it, such as with string formatting.

Is this even possible?

Thanks!

2

Best Answer


You can use ljust() and rjust() of string objects in python:

customer = 'John Doe'balance = 39.99output = customer.ljust(15, '.') + str(balance).rjust(10, '.')print(output)#John Doe............39.99

Depending on format you need, you can tune it with changing the widths or adding space characters.

If you did not want to have spaces on either side of the dots as the other answer would suggests, you can achieve that specifying formatting just as well:

"{:.<17s}{:.>8.2f}".format(customer, balance)

Would do 17 characters wide left aligned, . right padded string and 8 characters of right aligned, . left padded, float with precision of 2 decimal points.

You can do that same with an f-string (Python >=3.6):

f"{customer:.<17s}{balance:.>8.2f}"

However, if you also want to include the space on either side of the dots, it gets trickier. You can still do that, but you need to double pad / format or concatenate before filling in the gap:

"{:.<16s}{:.>9s}".format(f"{customer} ", f" {balance:>.2f}")

But I would be somewhat at pain to call that more elegant.

You could also do all that with formatting:

# Fill in with calculated number of ".""{} {} {:.2f}".format(customer,"."*(25 - (2 + len(customer) + len(f"{balance:.2f}"))),balance)# Similarly used for calculated width to pad with ".""{} {:.^{}s} {:.2f}".format(customer,"",25 - (2 + len(customer) + len(f"{balance:.2f}")),balance)

But again, more elegant is it really not.