Magic Liquid
Magic Liquid

Reputation: 1

Count the occurence of a list of items in a string?

How will I be able to count the number of time a list of items are repeated in a string. For example how can I search through string and check the number of times this list has been repeated in string?

list = ('+','-','*','/')
string = "33+33-33*33/33"

Upvotes: 0

Views: 64

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160687

Firstly, don't use a name like list, it masks the built-in name list [See: Built-in Methods] and that can lead to some subtle bugs.

After that, there's ways to do this. The crucial thing to have in mind is that objects like strings come along with a plethora of methods [See: String Methods] that act on them. One of these methods is str.count(sub) which counts the number of times sub occurs in your string.

So, creating a count for every element in lst could be done by using a for loop:

lst = ('+','-','*','/')
string = "33+33-33*33/33"
for i in lst:
    print("Item ", i, " occured", str(string.count(i)), "times")

str(string.count(i)) transforms the integer result of string.count to an str object so it can be printed by print.

This prints out:

Item  +  occured 1 times
Item  -  occured 1 times
Item  *  occured 1 times
Item  /  occured 1 times

After getting more accustomed to Python you could use a comprehension to create a list of the results and supply them to print:

print(*["Item {} occured {} times".format(x, string.count(x)) for x in lst], sep='\n')

which prints a similar result.

Finally, make sure you read the Tutorial available on the Python documentation website, it'll help you get acquainted with the language.

Upvotes: 1

Related Questions