+ 1
Count method for 2 or more elements in a string
Can I check more then 1 element in a list by using the count method?
13 ответов
+ 4
list has a count() method.
lst = [1,2,3,4,5,4,6,7,3,2,4,4,5,4]
print(lst.count(4)
# output: 5
here is also a sample with a list containing trings:
lst2 = ['abcdef','tfdcsefxs','nbbcdc','xzabef','ef']
cnt = 0
for i in lst2:
if i.count('ef') > 0:
cnt += 1
print(cnt)
# or:
print(len([i for i in lst2 if i.count('ef')]))
+ 4
David, you can run a modified version of :
print('ef: ',txt.count('ef'))
Instead of having 'ef' or 'gh' or whatever fixed in the code, you can put the 'strings to search' in a separate list. Then run the code line from above in a for loop and feed the search strings from the list. It's not too much to change. I wish you a great success!
+ 3
here the answers to your last quetions:
# ----------
lst = [1,2,3,4,5,4,6,7,3,2,4,4,5,4]
print(lst.count(4)+lst.count(5)) # if you are counting both together
print('4:',lst.count(4),', 5:',lst.count(5)) # if you count them separate
# ----------
txt = 'abcdef tfdcsefxs nbbcdc xzabef ef'
print('ef: ',txt.count('ef')) # string also has a count() method
+ 2
I like this elegant and pythonic solution by Lothar :
print(len([i for i in lst2 if i.count('ef')]))
+ 1
Yes, that can do it. I want to search for 7 elements, and it makes it inefficient running it again and again.
Thank you.
0
With len() you get the number of elements in a list
0
I'd like to count specific elements, not all the string.
0
How? Couldn't get it to work on more than one element.
0
You could call count separately and add the results
0
For 10 or more elements it isn't efficient enough. Thanks.
0
by filter them out maybe ?
[character for character in thestring if character == thecharyourelookingfor]
then you can find the size of the result.
pretty sure its not the most optimal way
0
With lists there is counter (). I'm looking for a method with strings.
In addition, in your sample, how can I count 4 and 5?
0
What would I do if I want to count not only 'ef' but also 'gh'? Together. Total sum.