Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count Number of Lowercase Characters in a String in Python Program
When you need to count the number of lowercase characters in a string, Python provides the islower() method which can be combined with a simple for loop to achieve this task.
Using islower() Method with for Loop
The islower() method returns True if the character is a lowercase letter, and False otherwise ?
my_string = "Hi there how are you"
print("The string is")
print(my_string)
my_counter = 0
for i in my_string:
if(i.islower()):
my_counter = my_counter + 1
print("The number of lowercase characters in the string are:")
print(my_counter)
The string is Hi there how are you The number of lowercase characters in the string are: 15
Using List Comprehension
A more concise approach using list comprehension and the sum() function ?
my_string = "Hi there how are you"
lowercase_count = sum(1 for char in my_string if char.islower())
print(f"The string: {my_string}")
print(f"Number of lowercase characters: {lowercase_count}")
The string: Hi there how are you Number of lowercase characters: 15
How It Works
A string is defined and displayed on the console.
The string is iterated over using a
forloop.Each character is checked using the
islower()method to determine if it's a lowercase letter.A counter is incremented for each lowercase character found.
The final count is displayed as output.
Comparison of Methods
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| for loop | High | Good | Longer |
| List comprehension | Medium | Better | Shorter |
Conclusion
Use the islower() method with a for loop for clear, readable code. For more concise solutions, list comprehension with sum() provides better performance and shorter code.
