Fixing Python’s title Function
home // page // Fixing Python’s title Function

Fixing Python’s title Function

Python’s title function has some weird side-effects when you’re titlizing a string like, for example, a street name:

>>> "62nd".title()
"62Nd"
>>> "West 62nd st.".title()
"West 62Nd St."

Here’s how you can fix this:

import re

def fixed_title(input_string):
    parts = re.split(r'\s', input_string)

    for idx, value in enumerate(parts):
        if re.match(r'[A-Za-z]', value[0]):
            parts[idx] = value[0].upper() + value[1:]

    return ' '.join(parts)

A simple fix that produces the right result:

>>> fixed_title("West 62nd st.")
"West 62nd St."

 

 

Trackbacks for this post

Leave a Reply

Your email address will not be published. Required fields are marked *