pythonlisthuman-readable

Grammatically correct human readable string from list (with Oxford comma)


I want a grammatically correct human-readable string representation of a list. For example, the list ['A', 2, None, 'B,B', 'C,C,C'] should return the string A, 2, None, B,B, and C,C,C. This contrived example is somewhat necessary. Note that the Oxford comma is relevant for this question.

I tried ', '.join(seq) but this doesn't produce the expected result for the aforementioned example.

Note the preexisting similar questions:


Solution

  • This function works by handling small lists differently than larger lists.

    from typing import Any, List
    
    def readable_list(seq: List[Any]) -> str:
        """Return a grammatically correct human readable string (with an Oxford comma)."""
        # Ref: https://stackoverflow.com/a/53981846/
        seq = [str(s) for s in seq]
        if len(seq) < 3:
            return ' and '.join(seq)
        return ', '.join(seq[:-1]) + ', and ' + seq[-1]
    

    Usage examples:

    readable_list([])
    ''
    
    readable_list(['A'])
    'A'
    
    readable_list(['A', 2])
    'A and 2'
    
    readable_list(['A', None, 'C'])
    'A, None, and C'
    
    readable_list(['A', 'B,B', 'C,C,C'])
    'A, B,B, and C,C,C'
    
    readable_list(['A', 'B', 'C', 'D'])
    'A, B, C, and D'