Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • How to print a list in Python "nicely" doesn't concern with a grammatically correct human-readable string.
  • Grammatical List Join in Python is without the Oxford comma. The example and answers there are correspondingly different and they do not work for my question.
like image 302
Asclepius Avatar asked Dec 06 '22 10:12

Asclepius


1 Answers

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'
like image 151
Asclepius Avatar answered May 20 '23 11:05

Asclepius