Commits

Mike Orr committed bccfea2

New helper series() in webhelpers.text.

  • Participants
  • Parent commits 4053a49

Comments (0)

Files changed (2)

 * Include a faster version of cgi.escape for use by the literal object.
 * Fixed bug in SimplerXMLGenerator that the FeedGenerator uses, so that
   it doesn't use a {} arg.
+* New helpers:
+  - ul() and ol() in webhelpers.html.tags.
+  - series() in webhelpers.text.
 
 0.6 (07/08/2008)
 * Add webhelpers.html.builder to generate HTML tags with smart escaping,

File webhelpers/text.py

         end = None
     return "".join(result)
 
+def series(items, conjunction="and", strict_commas=True):
+    """Format a series for use in English text.
+
+    Examples:
+
+    >>> series(["A", "B", "C"])
+    'A, B, and C'
+    >>> series(["A", "B", "C"], "or")
+    'A, B, or C'
+    >>> series(["A", "B", "C"], strict_commas=False)
+    'A, B and C'
+    >>> series(["A", "B"])
+    'A and B'
+    >>> series(["A"])
+    'A'
+    >>> series([])
+    ''
+    """
+    items = list(items)
+    length = len(items)
+    if length == 0:
+        return ""
+    if length == 1:
+        return items[0]
+    if length == 2:
+        strict_commas = False
+    nonlast = ", ".join(items[:-1])
+    last = items[-1]
+    comma = strict_commas and "," or ""
+    return "%s%s %s %s" % (nonlast, comma, conjunction, last)