在python中,有没有一种字符串方法来大写首字母缩写词?

2024-10-03 11:26:00 发布

您现在位置:Python中文网/ 问答频道 /正文

这很好:

import string string.capwords("proper name") 'Proper Name'

这不太好:

string.capwords("I.R.S") 'I.r.s'

有没有字符串方法来做capwords以便它能容纳缩略词?在


Tags: 方法字符串nameimportstring缩略词propercapwords
3条回答

这可能有用:

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)

这是一个测试:

^{pr2}$

即使有这样的功能,当被要求处理“国税局”时,它会怎么做?就连国税局都自称“国税局”,没有点。在

不,在标准库中没有这种方法。在

相关问题 更多 >