Python: fixed-length string multiple variables left and right aligned

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 = '..'

    # 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
+4
source share
5 answers

, , :

>>> line = ['8', '45', '1']
>>> station = ['station A', 'long station', 'great station']
>>> eta = ['8','10', '25']
>>> MAX = 20

>>> for i in range(3):
    m_str = '{0}: {1}'.format(line[i], station[i]) #aligns left
    m_str = m_str + ' '*(MAX-len(str)-len(eta[i])) + eta[i] #aligns right
    print m_str

, ( 20) len m_str , (len(eta[i])).

, , len(m_str) 20 .

:

8: station A       8
45: long station  10
1: great station  25
+3

:

tmp = '{}: {}'.format(line, station)
print('{}{:{}}'.format(tmp, eta, 20-len(tmp)))

:

trains = ((8, 'station A', 8), (45, 'long station', 10), (1, 'great station', 25))
for line, station, eta in trains:
    tmp = '{}: {}'.format(line, station)
    print('{}{:{}}'.format(tmp, eta, 20-len(tmp)))

Prints:

8: station A       8
45: long station  10
1: great station  25
+1

. . 20 :

print('{0}: {1} {2:<20}'.format(line, station, eta)[:20])
0

.rjust() .ljust() , ,

lst = [[8, "station A", 8], [45, "long station", 10], [1, "great station", 25]]
for i in lst:
    print str(i[0]).ljust(2)+":"+i[1]+str(i[2]).rjust(20 - (len(i[1])+3))

:

8 :station A       8
45:long station   10
1 :great station  25
0

, , prettytable :

from prettytable import PrettyTable

table = PrettyTable(['line', 'station', 'eta'])

table.add_row([8, 'station A', 10])
table.add_row([6, 'station B', 20])
table.add_row([5, 'station C', 15])

Since it is not built into Python, you will need to install it yourself from the package index here .

0
source

All Articles