Today i will teach you one of the favorite interview question related to python coding interview.
How you can calculate the count of a character repeats in a string.
Lets find out what happened here !!
data = ("Hi hello how are you")
data1 = list(data.lower())
print(data1)
print(data1.count("h")) #Using inbuild method
scount = 0
#Using for loop
for num in data1:
if num == "h":
scount += 1
print("Total count:",scount)
we have taken a variable called data where the string is present.
in data1 we are doing all lower case to string. Because string may contain both Upper case and Lowe case.
Then printing the data1.
Here we are try to find how many H or h is present in the given string.
Using data1.count("h") ==> It will show the output as 3
Also we can use loop to iterate through every single character. Interview may ask not to use inbuilt function to calculate.
So using for loop too we can do the same.
Now you learn something today. Please leave a comment , like and share.
0 Comments