I am fairly new to Python and try to format a string for ouput on a LCD-display.
I would like to output a formatted table of train departures
- the display has a fixed length of 20 characters (20x4)
- I have 3 string-variables with variable length (line, station, eta)
- 2 of them should be left-aligned (line, station), while the third one should go right aligned
Example:
8: station A 8
45: long station 10
1: great station 25
I have played around with various things, but I am not able to define the max length for the overall string, but only 1 variable:
print('{0}: {1} {2:<20}'.format(line, station, eta))
Any tips and hints are much appreciated!
--- Solution based on @Rafael Cardoso s answer:
print(format_departure(line, station, eta))
def format_departure(line, station, eta):
max_length = 20
truncate_chars = '..'
# add a leading space to the eta - just to be on the safe side
eta = ' ' + eta
output = '{0}: {1}'.format(line, station) # aligns left
# make sure that the first part is not too long, otherwise truncate
if (len(output + eta)) > max_length:
# shorten for truncate_chars + eta + space
output = output[0:max_length - len(truncate_chars + eta)] + truncate_chars
output = output + ' '*(max_length - len(output) - len(eta)) + eta # aligns right
return output
tabulate:txt.arboreus.com/2013/03/13/pretty-print-tables-in-python.html (pypi.python.org/pypi/tabulate)