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: m.group(0).lower(), value.title())
    return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)

Happy Coding

5 Responses

  1. tsr #

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

    Reply
    • nitin #

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

      Reply
  2. xcubelabs #

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

    BTW very nice blog mate. :)

    Reply
  3. Phil #

    In python:

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

    Reply
    • ASf #

      Bloody rippa

      Reply

Leave a Reply