Python title() with apostrophes Python title() with apostrophes python python

Python title() with apostrophes


If your titles do not contain several whitespace characters in a row (which would be collapsed), you can use string.capwords() instead:

>>> import string>>> string.capwords("john's school")"John's School"

EDIT: As Chris Morgan rightfully says below, you can alleviate the whitespace collapsing issue by specifying " " in the sep argument:

>>> string.capwords("john's    school", " ")"John's    School"


This is difficult in the general case, because some single apostrophes are legitimately followed by an uppercase character, such as Irish names starting with "O'". string.capwords() will work in many cases, but ignores anything in quotes. string.capwords("john's principal says,'no'") will not return the result you may be expecting.

>>> capwords("John's School")"John's School">>> capwords("john's principal says,'no'")"John's Principal Says,'no'">>> capwords("John O'brien's School")"John O'brien's School"

A more annoying issue is that title itself does not produce the proper results. For example, in American usage English, articles and prepositions are generally not capitalized in titles or headlines. (Chicago Manual of Style).

>>> capwords("John clears school of spiders")'John Clears School Of Spiders'>>> "John clears school of spiders".title()'John Clears School Of Spiders'

You can easy_install the titlecase module that will be much more useful to you, and does what you like, without capwords's issues. There are still many edge cases, of course, but you'll get much further without worrying too much about a personally-written version.

>>> titlecase("John clears school of spiders")'John Clears School of Spiders'


I think that can be tricky with title()

Lets try out something different :

def titlize(s):    b = []    for temp in s.split(' '): b.append(temp.capitalize())    return ' '.join(b)titlize("john's school")// You get : John's School

Hope that helps.. !!