Search code examples
pythonstringacronymcapitalize

is there a string method to capitalize acronyms in python?


This is good:

import string
string.capwords("proper name")

Out: 'Proper Name'

This is not so good:

string.capwords("I.R.S")

Out: 'I.r.s'

Is there no string method to do capwords so that it accomodates acronyms?


Solution

  • This might work:

    import re
    
    def _callback(match):
        """ This is a simple callback function for the regular expression which is 
            in charge of doing the actual capitalization. It is designed to only 
            capitalize words which aren't fully uppercased (like acronyms).
        """
        word = match.group(0)
        if word == word.upper():
            return word
        else:
            return word.capitalize()
    
    def capwords(data):
        """ This function converts `data` into a capitalized version of itself. This 
            function accomidates acronyms.
        """
        return re.sub("[\w\'\-\_]+", _callback, data)
    

    Here is a test:

    print capwords("This is an IRS test.")    # Produces: "This Is An IRS Test."
    print capwords("This is an I.R.S. test.") # Produces: "This Is An I.R.S. Test."