diff options
author | Raymond Hettinger <python@rcn.com> | 2009-09-29 06:22:28 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2009-09-29 06:22:28 (GMT) |
commit | b8b0ba1fa0b04762ab808b66f1f6bb5e066540cf (patch) | |
tree | 438c0c9c169e92207b0f349210a890c410a2602b /Doc | |
parent | 26713cade1e8e2e2458062c4f0be0b53ae436753 (diff) | |
download | cpython-b8b0ba1fa0b04762ab808b66f1f6bb5e066540cf.zip cpython-b8b0ba1fa0b04762ab808b66f1f6bb5e066540cf.tar.gz cpython-b8b0ba1fa0b04762ab808b66f1f6bb5e066540cf.tar.bz2 |
Issue 7008: Better document str.title and show how to work around the apostrophe problem.
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/library/stdtypes.rst | 24 |
1 files changed, 22 insertions, 2 deletions
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 115eff4..8cc52c2 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -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) |