April Post
April Post

Reputation: 1

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.

Upvotes: 0

Views: 151

Answers (3)

Manuel
Manuel

Reputation: 706

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()

Upvotes: 0

Chris Martin
Chris Martin

Reputation: 30746

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'

Upvotes: 2

Super Mario
Super Mario

Reputation: 939

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

Upvotes: 0

Related Questions