简体   繁体   中英

I'm trying to figure out how to count how many times a letter is capitalized in a string sentence in Python

I was asked to capitalize the first letter of each word in a sentence and return the number of letters that have been capitalized. I have this so far:

text = input('Enter a sample text:\n')
sentence = text.split('.')
    for i in sentence:
        print (i.strip().capitalize()+". ",end='')

I just need to figure out how to count how many times a letter has been capitalized.

There is a title function in the standard library to capitalize the first letter in each word:

>>> x = 'one two Three four'

>>> x.title()
'One Two Three Four'

Then the only thing that's left is to count the number of characters that differ between the original string and the modified string. A comprehension can express this nicely:

>>> sum(1 for (a, b) in zip(x, x.title()) if a != b)
3

Please note, however, that this approach only works if title-case string has the same length as the original string. For example, it will not work if the input string contains ß , because:

>>> 'ß'.title()
'Ss'

Separate each line into words, and the compare if a word is capitalized and count it.

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)

Edit, there are a better way to capitalize each letter, using title.

text_out = text_out.title()
counter = 0
for i in range(len(txt)):
    if txt[i] != txt.title()[i]:
        counter += 1
print(counter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM