0
# List Formatting
1
2
Convert Python lists into natural language strings with proper comma placement and conjunction usage, following standard English grammar rules.
3
4
## Capabilities
5
6
### Natural List
7
8
Converts a list of items into human-readable text with appropriate comma separation and conjunction placement.
9
10
```python { .api }
11
def natural_list(items: list[Any]) -> str:
12
"""
13
Convert a list of items into a human-readable string.
14
15
Args:
16
items: List of items to convert (any type that can be stringified)
17
18
Returns:
19
String with commas and 'and' in appropriate places
20
21
Examples:
22
>>> natural_list(["one", "two", "three"])
23
'one, two and three'
24
>>> natural_list(["one", "two"])
25
'one and two'
26
>>> natural_list(["one"])
27
'one'
28
>>> natural_list([])
29
''
30
"""
31
```
32
33
## Grammar Rules
34
35
The function follows standard English grammar conventions:
36
37
- **Single item**: Returns the item as-is
38
- **Two items**: Joins with " and " (no comma)
39
- **Three or more items**: Uses commas between all items except the last, which is preceded by " and "
40
41
Note: This follows the style without the Oxford comma (no comma before "and").
42
43
## Usage Examples
44
45
### Basic List Formatting
46
47
```python
48
import humanize
49
50
# Single item
51
print(humanize.natural_list(["apple"]))
52
# "apple"
53
54
# Two items
55
print(humanize.natural_list(["apple", "banana"]))
56
# "apple and banana"
57
58
# Three items
59
print(humanize.natural_list(["apple", "banana", "cherry"]))
60
# "apple, banana and cherry"
61
62
# Many items
63
items = ["red", "green", "blue", "yellow", "purple"]
64
print(humanize.natural_list(items))
65
# "red, green, blue, yellow and purple"
66
```
67
68
### Mixed Data Types
69
70
The function works with any items that can be converted to strings:
71
72
```python
73
import humanize
74
75
# Numbers
76
print(humanize.natural_list([1, 2, 3, 4]))
77
# "1, 2, 3 and 4"
78
79
# Mixed types
80
print(humanize.natural_list(["item", 42, 3.14, True]))
81
# "item, 42, 3.14 and True"
82
83
# Objects with string representations
84
from datetime import date
85
dates = [date(2023, 1, 1), date(2023, 6, 15), date(2023, 12, 31)]
86
print(humanize.natural_list(dates))
87
# "2023-01-01, 2023-06-15 and 2023-12-31"
88
```
89
90
### Empty and Edge Cases
91
92
```python
93
import humanize
94
95
# Empty list
96
print(humanize.natural_list([]))
97
# ""
98
99
# List with None values
100
print(humanize.natural_list([None, "something", None]))
101
# "None, something and None"
102
103
# List with empty strings
104
print(humanize.natural_list(["", "middle", ""]))
105
# ", middle and "
106
```
107
108
### Practical Applications
109
110
#### Error Messages
111
112
```python
113
import humanize
114
115
def validate_required_fields(data, required):
116
missing = [field for field in required if field not in data]
117
if missing:
118
fields_text = humanize.natural_list(missing)
119
raise ValueError(f"Missing required fields: {fields_text}")
120
121
# Example usage
122
try:
123
validate_required_fields({"name": "John"}, ["name", "email", "phone"])
124
except ValueError as e:
125
print(e) # "Missing required fields: email and phone"
126
```
127
128
#### Status Reports
129
130
```python
131
import humanize
132
133
def format_status_report(completed, pending, failed):
134
parts = []
135
if completed:
136
parts.append(f"{len(completed)} completed")
137
if pending:
138
parts.append(f"{len(pending)} pending")
139
if failed:
140
parts.append(f"{len(failed)} failed")
141
142
return f"Tasks: {humanize.natural_list(parts)}"
143
144
# Example usage
145
print(format_status_report([1, 2, 3], [4, 5], [6]))
146
# "Tasks: 3 completed, 2 pending and 1 failed"
147
```
148
149
#### User Interface Text
150
151
```python
152
import humanize
153
154
def format_permissions(user_permissions):
155
readable_permissions = [p.replace('_', ' ').title() for p in user_permissions]
156
return f"User has permissions: {humanize.natural_list(readable_permissions)}"
157
158
# Example usage
159
permissions = ["read_posts", "write_comments", "delete_own_content"]
160
print(format_permissions(permissions))
161
# "User has permissions: Read Posts, Write Comments and Delete Own Content"
162
```
163
164
## Implementation Notes
165
166
- All items in the list are converted to strings using `str()`
167
- The function handles any iterable that can be converted to a list
168
- Empty lists return empty strings
169
- Single-item lists return just that item as a string
170
- The conjunction "and" is hard-coded in English; for internationalization, use the i18n module