+ 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?

14th Jan 2020, 12:58 PM
David Orlian
13 Answers
+ 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')]))
14th Jan 2020, 3:23 PM
Lothar
Lothar - avatar
+ 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!
15th Jan 2020, 4:25 PM
Lothar
Lothar - avatar
+ 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
14th Jan 2020, 7:23 PM
Lothar
Lothar - avatar
+ 2
I like this elegant and pythonic solution by Lothar : print(len([i for i in lst2 if i.count('ef')]))
15th Jan 2020, 12:13 PM
Prof. Dr. Zoltán Vass
+ 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.
15th Jan 2020, 4:31 PM
David Orlian
0
With len() you get the number of elements in a list
14th Jan 2020, 1:19 PM
Jnn
Jnn - avatar
0
I'd like to count specific elements, not all the string.
14th Jan 2020, 1:23 PM
David Orlian
0
How? Couldn't get it to work on more than one element.
14th Jan 2020, 1:28 PM
David Orlian
0
You could call count separately and add the results
14th Jan 2020, 1:32 PM
Jnn
Jnn - avatar
0
For 10 or more elements it isn't efficient enough. Thanks.
14th Jan 2020, 1:35 PM
David Orlian
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
14th Jan 2020, 1:41 PM
Taste
Taste - avatar
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?
14th Jan 2020, 3:58 PM
David Orlian
0
What would I do if I want to count not only 'ef' but also 'gh'? Together. Total sum.
15th Jan 2020, 1:10 PM
David Orlian