是否有一种字符串方法可在python中将首字母缩写大写? [英] is there a string method to capitalize acronyms in python?
本文介绍了是否有一种字符串方法可在python中将首字母缩写大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这很好:
导入字符串
字符串.capwords(专有名称)
'专有名称'
import string string.capwords("proper name") 'Proper Name'
这不是很好:
string.capwords ( IRS)
'Irs'
string.capwords("I.R.S") 'I.r.s'
是否没有字符串方法可以用来写单词,所以它可以容纳首字母缩写词?
Is there no string method to do capwords so that it accomodates acronyms?
推荐答案
这可能有效:
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)
这是一个测试:
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."
这篇关于是否有一种字符串方法可在python中将首字母缩写大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文