Count the number of capital letters in a string in Python
Hey guys
In this tutorial, we will learn how to count the number of capital letters in a given string in Python.
First, we will know what is our problem. we have a given string that contains the number of the upper case letters and the number of lower case letters. Now we have to write such a type of code that counts the number of the uppercase letters in the string and print it as the output on the string.
Now let’s move towards our coding portion.
Finding the number of uppercase letters in the string
first, we know how to take the input string from the user
name=input("enter the string")
or we can use another method for accepting string because the above can accept any type of data as a string
name=str(input("enter the string))
By the help of the above methods, we can take a string as input.
There is a method in python that is used to return true if the letter is uppercase otherwise it will return false.
string.isupper()
isupper() function does not contain any parameter
- It will return true if all the letters in the string are in uppercase
- it will return false if the string contains one or more lowercase letters
Now let us move towards the coding portion of the problem
name=str(input("enter the string")) count=0 for i in name: if i.isupper(): count=count+1 print("The number of capital letters found in the string is:-",count)
According to the above piece of code, the variable of the string is called name. and a counter variable will be initialized count=0 which is used to count the number of capital letters. now we start a for loop using the values of the name as i then if statement checks that the character is in uppercase or not if yes, then if block will execute, otherwise the loop will continue till the last character of the string and checks each and every character.
Now the output will be:-
enter the string ABCDEFGHijklmnOPQ The number of capital letters found in the string is:- 11
As we can see there are a total of 11 capital letters in the given string
You can also check:
Leave a Reply