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
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.
Similar Questions
Write a python program to print the number of occurrences of a substring into a line
Write a python program to count the number of palindrome strings that occurred in the given string.
Write a python program to count the number of characters of alphabets 'O' and 'i' from the given file
Python program that accepts a string and calculate the number of digits and letters and space
Write a program to count number of words in a given string whose length is greater than 3.For example:Input Resultpython is easier than C3
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.