Make format string align integer after character

61 views Asked by At

I'm trying to make a format string that does something like the following.

I lost 10 turtles        Total: 20 Turtles
I lost  5 turtles        Total: 15 Turtles

I came up with this string "I lost {:>2} {:<13}Total:{:<}".format(10,"turtles",20) is there anyway to get rid of the {:<13} and [,"turtles"] but still produce the same result?

2

There are 2 answers

3
falsetru On BEST ANSWER

Put turtles inside the format string:

>>> "I lost {:>2} {:<13}Total:{:<}".format(10, "turtles", 20)
'I lost 10 turtles      Total:20'
>>> "I lost {:>2} turtles      Total:{:<}".format(10, 20)  # <--------
'I lost 10 turtles      Total:20'

>>> "I lost {:>2} {:<13}Total:{:<} Turtles".format(10, "turtles", 20)
'I lost 10 turtles      Total:20 Turtles'
>>> "I lost {:>2} turtles      Total:{:<} Turtles".format(10, 20)  # <--------
'I lost 10 turtles      Total:20 Turtles'
1
Mazdak On

what about this ?:

>>> "I lost {:<20} Total:{:<}".format("10 turtles","20 turtles")
'I lost 10 turtles           Total:20 turtles'

or a function :

>>> def formater(i,j):
...  return "I lost {:<20} Total:{:<}".format("{} turtles".format(i),"{} Turtles".format(j))
... 
>>> formater(10,20)
'I lost 10 turtles           Total:20 Turtles'