将现有大写字母保留在字符串中

时间:2013-07-07 10:22:37

标签: python string python-3.x

我使用以下代码将每个单词的第一个字母更改为大写,除了一些琐碎的单词(a,等等)

f = open('/Users/student/Desktop/Harry.txt').readlines()[2]
new_string = f.title()
print (new_string)

我还想做的是,如上所述,这些例外词没有大写,但也有任何已经有大写字母的单词(例如中国,新南威尔士州),这些字母将被保留。

2 个答案:

答案 0 :(得分:1)

这样的事情:

使用str.capitalize

为什么?

>>> "CAN'T".title()
"Can'T"

>>> "CAN'T".capitalize()
"Can't"

<强>代码:

>>> strs = """What i would also like to do is have those exception words not capitalised as 
stated above but also have that any word that already has capitals letters
( For e.g. CHINA, NSW etc. ) that those letters will be retained."""
>>> words = {'a','of','etc.','e.g.'}  #set of words that shouldn't be changed
>>> lis = []
for word in strs.split():
    if word not in words and not word.isupper(): 
        lis.append(word.capitalize())
    else:    
        lis.append(word)
...         
>>> print " ".join(lis)
What I Would Also Like To Do Is Have Those Exception Words Not Capitalised As Stated Above But Also Have That Any Word That Already Has Capitals Letters ( For e.g. CHINA, NSW etc. ) That Those Letters Will Be Retained.

答案 1 :(得分:0)

对于第一个要求,您可以创建包含例外词的列表:

e_list = ['a', 'of', 'the'] # for example

然后你可以使用isupper()运行这样的东西来检查字符串是否已全部大写:

new = lambda x: ' '.join([a.title() if (not a in e_list and not a.isupper()) else a for a in x.split()])

测试:

f = 'Testing if one of this will work EVERYWHERE, also in CHINA, in the run.'

print new(f)
#Testing If One of This Will Work EVERYWHERE, Also In CHINA, In the Run.