Take the 2-minute tour ×

On Python 3 I am trying to write a function format_list(items) that takes a list items containing 1 or 2 string elements and returns a string containing the elements. Assume that the list being passed will always contain one or two elements (ie, it won't be empty and it won't contain more than two elements).

The conditions are:

  1. If the list contains a single element, that element is returned by the function, unchanged.
  2. If the list contains two elements, they are returned in a single string with the first element left justified in a field of width 10 followed by a vertical bar ('|') followed by the second element right justified in a field of width 10. You may assume the elements are strings with at most 10 characters each.

So print(format_list(['abc'])) would produce:


And print(format_list(['Dave', '14'])) would produce:

Dave   |   14

I have no idea where to even start....

share|improve this question
you can start with the Python Documentation –  Serdalis Mar 25 '13 at 22:00
more specifically, format –  georg Mar 25 '13 at 22:03
Thanks, I have read it before but maybe I need a refresher... –  jevans Mar 25 '13 at 22:34

3 Answers 3

up vote 1 down vote accepted
def format_list(l):
    if len(l)==1: return l[0]
        return '{:<10}|{:>10}'.format(l[0],l[1])

for l in [['abc'],['Dave', '14']]:        


Dave      |        14

Look at the .format method and the .format mini language.

share|improve this answer
Does not right justify the second list item. –  Ethan Furman Mar 25 '13 at 22:06
Now it's centering... –  Ethan Furman Mar 25 '13 at 22:13
@EthanFurman: Like u, I didn't want to look it up. Fixed –  dawg Mar 25 '13 at 22:16
Thanks, that makes so much sense. –  jevans Mar 25 '13 at 22:33

This sounds like homework, so a couple clues to get you going:

  • % formatting (e.g. "Hello %s!" % some_var --> "Hello World!" if some_var == "World")

  • len(some_list) --> number of items in list

Oh, and since I don't want to look it up:

"%10s" % 'word' --> ......word ( a dot is a space )

"%-10s" % 'word' --> word......

share|improve this answer
def format_list(my_list)
        return my_list[0].ljust(10) + '|' + my_list[1].rjust(10)
    except IndexError: return my_list
share|improve this answer
This fails the first condition: it should return the single element, not the list itself. –  Ethan Furman Feb 12 at 20:55

Your Answer


