How to Count the Number of Letters in a String in Python?

Estimated read time 1 min read

You can count the number of letters in a string in Python by iterating through the string and checking each character if it is a letter using the isalpha() method. Here’s an example:

# Input string
input_string = "Hello World"

# Initialize letter count
letter_count = 0

# Iterate through each character in the string
for char in input_string:
    # Check if the character is a letter
    if char.isalpha():
        # Increment letter count
        letter_count += 1

# Print the letter count
print(f"Number of letters: {letter_count}")

In this example, we first define the input string for which we want to count the letters. Then, we initialize the letter_count variable to 0. Next, we use a for loop to iterate through each character in the input string. Inside the loop, we use the isalpha() method to check if the character is a letter. If it is, we increment the letter_count variable by 1. Finally, we print the letter count using a print() statement. Note that the isalpha() method returns True if the character is an alphabet letter (a-z or A-Z), and False otherwise, allowing us to count the number of letters in the string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply