]> granicus.if.org Git - python/commitdiff
Issue 7008: Better document str.title and show how to work around the apostrophe...
authorRaymond Hettinger <python@rcn.com>
Tue, 29 Sep 2009 06:22:28 +0000 (06:22 +0000)
committerRaymond Hettinger <python@rcn.com>
Tue, 29 Sep 2009 06:22:28 +0000 (06:22 +0000)
Doc/library/stdtypes.rst

index 115eff40de91c2c003c8270440991bd8781e769a..8cc52c21283a9bb66b5b1e5355f7e231d52a6296 100644 (file)
@@ -1126,8 +1126,28 @@ functions based on regular expressions.
 
 .. method:: str.title()
 
-   Return a titlecased version of the string: words start with uppercase
-   characters, all remaining cased characters are lowercase.
+   Return a titlecased version of the string where words start with an uppercase
+   character and the remaining characters are lowercase.
+
+   The algorithm uses a simple language-independent definition of a word as
+   groups of consecutive letters.  The definition works in many contexts but
+   it means that apostrophes in contractions and possessives form word
+   boundaries, which may not be the desired result::
+
+        >>> "they're bill's friends from the UK".title()
+        "They'Re Bill'S Friends From The Uk"
+
+   A workaround for apostrophes can be constructed using regular expressions::
+
+        >>> import re
+        >>> def titlecase(s):
+                return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
+                              lambda mo: mo.group(0)[0].upper() +
+                                         mo.group(0)[1:].lower(),
+                              s)
+
+        >>> titlecase("they're bill's friends.")
+        "They're Bill's Friends."
 
 
 .. method:: str.translate(map)