[英]Keeping existing capital letters in string
我正在使用以下代碼將每個單詞的首字母更改為大寫字母,但一些瑣碎的字母(a,of等)除外
f = open('/Users/student/Desktop/Harry.txt').readlines()[2]
new_string = f.title()
print (new_string)
我還想做的是讓那些例外詞沒有如上所述那樣大寫,但是還要讓任何已經有大寫字母的單詞(例如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.
對於第一個要求,您可以創建一個包含異常詞的列表:
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.