In Python, you can count the number of uppercase and lowercase characters in a string using a loop and the isupper()
and islower()
string methods. Here’s an example:
# Input string
text = "Hello World"
# Initialize counters
upper_count = 0
lower_count = 0
# Loop through each character in the string
for char in text:
# Check if the character is uppercase
if char.isupper():
upper_count += 1
# Check if the character is lowercase
elif char.islower():
lower_count += 1
# Print the counts
print("Uppercase count:", upper_count)
print("Lowercase count:", lower_count)
Output:
Uppercase count: 2
Lowercase count: 8
In this example, the isupper()
and islower()
methods are called on each character in the input string text
. If the character is uppercase, upper_count
is incremented, and if the character is lowercase, lower_count
is incremented. Finally, the counts are printed.
+ There are no comments
Add yours