[英]I'm trying to figure out how to count how many times a letter is capitalized in a string sentence in Python
要求我將句子中每個單詞的首字母大寫,然后返回已大寫的字母數。 到目前為止,我有:
text = input('Enter a sample text:\n')
sentence = text.split('.')
for i in sentence:
print (i.strip().capitalize()+". ",end='')
我只需要弄清楚如何計算一個字母大寫的次數。
標准庫中有一個title
函數,用於將每個單詞的第一個字母大寫:
>>> x = 'one two Three four'
>>> x.title()
'One Two Three Four'
然后剩下的唯一事情就是計算原始字符串和修改后的字符串之間不同的字符數。 理解力可以很好地表達這一點:
>>> sum(1 for (a, b) in zip(x, x.title()) if a != b)
3
但是請注意,只有標題大小寫的字符串與原始字符串具有相同的長度時,此方法才有效。 例如,如果輸入字符串包含ß
,它將不起作用,因為:
>>> 'ß'.title()
'Ss'
將每一行分隔成多個單詞,然后比較一個單詞是否大寫並計數。
text = 'Enter a sample text:'
words = text.split()
count = 0
text_out = ''
for word in words:
if word != word.capitalize():
word = word.capitalize()
count += 1
text_out = text_out + ' ' + word
text_out = text_out.strip()
print(count)
編輯,有一種更好的方法是使用標題將每個字母大寫。
text_out = text_out.title()
counter = 0
for i in range(len(txt)):
if txt[i] != txt.title()[i]:
counter += 1
print(counter)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.