Title case a string in Python


2013-11-07

While writing a python program, I came upon the need to convert a string to title case, or to capitalize the initial character of each word.

Although PHP has ucwords(), Python does not partake in the "two methods for everything anyone has ever thought about". Here's a small function to give you title cased strings:

def title_case(line):
    return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])

This will turn a string like "my fancy string" into "My Fancy String".