Search code examples
pythonjoinstring

What's the best way to join an array into a readable list?


I've got an array listing days of the week:

days = ['Monday', 'Tuesday', 'Wednesday']

What's the easiest / best way to output it in a human readable format:

Monday, Tuesday and Wednesday

The best I have is rather ugly:

', '.join(days[:-2]+['']) + ' and '.join(days[-2:])

Solution

  • Why is everyone trying to force-fit this into a single expression?

    def comma_separated(lst):
        """
        >>> comma_separated(['a'])
        'a'
        >>> comma_separated(['a', 'b'])
        'a and b'
        >>> comma_separated(['a', 'b', 'c'])
        'a, b and c'
        """
        if len(lst) == 1:
            return lst[0]
        comma_part = ", ".join(lst[:-1])
        return "%s and %s" % (comma_part, lst[-1])
    
    if __name__ == "__main__":
        import doctest
        doctest.testmod()
    

    And remember, this is specific to English (and aside from "and", probably some other Western languages). Other languages have entirely different rules.