4

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
1

5 Answers 5

3

You can add spaces by making a calculation of how many spaces should be added in between station and eta :

>>> 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

The calculation would be to get the max length (in this case 20) minus the current len of m_str minus what will yet come (len(eta[i])).

Bear in mind that it assumes that len(m_str) will not be greater than 20 at this point.

Output:

8: station A       8
45: long station  10
1: great station  25
Sign up to request clarification or add additional context in comments.

1 Comment

I took your proposal and added some functionality to also account for line/station strings too long to display nicely.
1

Use a temporary string for the left part and its length:

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

Demo:

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

Comments

0

You can use slices to specify a max length. E.g. the following will only print the first 20 characters of the string resulting from the format:

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

Comments

0

You can also use .rjust() and .ljust() methods on given strings to set their alignment,

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))

Output:

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

Comments

0

It seems to me that you wish to create a table, so I suggest you use prettytable like so:

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])

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

3 Comments

Don't we need to import something for prettyTable ?
@anmol_uppal Thanks for the edit. What do you think of the library?
You are right, but I prefer including as few libraries as possible

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.