我正在使用以下代码将每个单词的首字母更改为大写,除了一些琐碎的单词(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.
关于python - 将现有大写字母保留在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511275/