Skip to main content
 首页 » 编程设计

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

2025年05月04日19傻小

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

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

我还想做的是让那些没有如上所述大写的异常(exception)词,但也有任何已经有大写字母的词(例如 CHINA,NSW),这些字母将被保留。

请您参考如下方法:

像这样:

使用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.