RegEx to Convert String in TitleCase (Python / Django)

During web development I very often come across a problem to convert any string into TitleCase. Those who don’t know title case is the style of writing having first letter as a majuscule (upper-case letter) and the remaining letters in minuscules (lower-case letters).

So here is the python function to do that:

def title(value):
    """Converts a string into titlecase."""
    t = re.sub("([a-z])'([A-Z])", lambda m:, value.title())
    return re.sub("\d([A-Z])", lambda m:, t)

Happy Coding

5 Responses

  1. tsr #

    so python doesn’t have ucfirst.. i am a php guy.

    • nitin #

      I think python doesn’t have it.
      As python is a generic language, not specifically a web language.

  2. xcubelabs #

    I have some experience with Python and I believe ucfirst is absent in it.

    BTW very nice blog mate. 🙂

  3. Phil #

    In python:

    >>> ‘some stuff in lower’.title()
    ‘Some Stuff In Lower’

    • ASf #

      Bloody rippa


Leave a Reply