是否有一个字符串方法来在python中大写首字母缩略词?

jam*_*day 0 python string acronym capitalize

这很好:

import string string.capwords("专有名称")'专有名称'

这不太好:

string.capwords("IRS")'Irs'

有没有字符串方法来做capwords以便它可以容纳首字母缩略词?

Eva*_*ark 5

这可能有效:

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)
Run Code Online (Sandbox Code Playgroud)

这是一个测试:

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."
Run Code Online (Sandbox Code Playgroud)