How to Count the Number of Occurrences of a Specific Letter in a String Using Python?

Estimated read time 1 min read

In Python, you can count the number of occurrences of a specific letter in a string by using a loop and iterating through each character in the string. Here’s an example:

# Define the input string
input_string = "Hello, world! The quick brown fox jumps over the lazy dog."

# Define the letter to count
letter_to_count = 'o'

# Initialize a counter variable
letter_count = 0

# Iterate through each character in the string
for char in input_string:
    # Check if the character matches the letter to count (case-sensitive)
    if char == letter_to_count:
        # Increment the counter
        letter_count += 1

# Print the result
print("The letter '{}' appears {} times in the string.".format(letter_to_count, letter_count))

Output:

The letter 'o' appears 5 times in the string.

In this example, a for loop is used to iterate through each character in the input_string. Inside the loop, an if statement checks if the character char matches the letter to count letter_to_count (case-sensitive comparison). If there is a match, the counter letter_count is incremented. Finally, the result is printed using a formatted string to display the letter and its count.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply