what should we do if we want to count specific string or int. like I want to know how many 'p' in my list = ['hello world lets play ping pong] is there any operator or method in python that I can use?
CodePudding user response:
You can do it using a simple for loop.
count = 0
test_str = "hello world lets play ping pong"
for i in test_str:
if i == 'p':
count = count 1
Or if you prefer you can do the following
count = test_str.count('p')
CodePudding user response:
count = 0
list = ["hello world lets play ping pong"]
for i in list[0]:
if i == 'p':
count = count 1
print(count)
output: 3
CodePudding user response:
It's not quite clear what your list looks like since you have not provided a valid list.
However assuming that your list looks something like below, try this -
l = ['hello','world', 'lets', 'play', 'ping', 'pong']
sum([i.count('p') for i in l])
3
If its a string and not a list, then it's even simpler -
l = ['hello world lets play ping pong']
l[0].count('p')
3
Read more about list.count() method here or str.count() here
