Knowee
Questions
Features
Study Tools

Write a Python program to count the number of occurrences of a specific character in a string

Question

Write a Python program to count the number of occurrences of a specific character in a string

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple Python program that counts the number of occurrences of a specific character in a string:

def count_char(string, target_char):
    count = 0
    for char in string:
        if char == target_char:
            count += 1
    return count

# Test the function
print(count_char("Hello World", "o"))  # Output: 2

In this program, we define a function count_char that takes a string and a target character as input. It initializes a counter count to 0. Then it iterates over each character in the string. If the character is equal to the target character, it increments the counter. Finally, it returns the count.

The test call count_char("Hello World", "o") counts the number of "o" characters in the string "Hello World", and prints the result.

This problem has been solved

Similar Questions

Write a python program to print the number of occurrences of a substring into a line

Write a Python program to find the occurrences of a character in a given word

Palindrome CountWrite a python program to count the number of palindrome strings that occurred in the given string. Input:The input consists of a string.Output:count number of palindrome strings

Define the function count_substring(string, substring) that finds how many times the substring appears in the given string.Example:string = "Python is a powerful language. I want to learn Python"substring = "Python"Expected Output:2

Write a python program to count the number of characters of alphabets 'O' and 'i' from the given file

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.