I am new to Python and am trying to format the string for output on the LCD.
I would like to display a formatted train departure table
- the display has a fixed length of 20 characters (20x4)
- I have 3 variable-length string variables (string, station, this)
- 2 of them should be left aligned (line, station), and the third should be aligned right
Example:
8: station A 8
45: long station 10
1: great station 25
I played with different things, but I can not determine the maximum length for a common string, but only 1 variable:
print('{0}: {1} {2:<20}'.format(line, station, eta))
Any tips and tricks are greatly appreciated!
--- Solution based on @Rafael Cardoso answer:
print(format_departure(line, station, eta))
def format_departure(line, station, eta):
max_length = 20
truncate_chars = '..'
eta = ' ' + eta
output = '{0}: {1}'.format(line, station)
if (len(output + eta)) > max_length:
output = output[0:max_length - len(truncate_chars + eta)] + truncate_chars
output = output + ' '*(max_length - len(output) - len(eta)) + eta
return output
Nogga source
share