Python count substrings
Question: How do I find how many times does substring appears in string? I have
molecular formula and if the letters are uppercase it is one element(e.g.H),
if it has first Upper case letter and second lower case than it is one
element(e.g.Ba), and if there is number after element i have to add that
number to elment

example: input : Ba4H2Ba5Li3

if i search Ba it should print number 9(i have Ba4 and Ba5, that is 9), if i
search H it should print 2(one letter H but number 2 after it), and Li it
should print number 3.


Answer: You can use Regular Expression, like this

    
    
    data = "Ba4H2Ba5Li3"
    import re
    result = {}
    for element, count in re.findall(r"([A-Z][a-z]?)(\d*)", data):
        result[element] = result.get(element, 0) + int(1 if count == "" else count)
    print result
    # {'H': 2, 'Ba': 9, 'Li': 3}
    

Now, you can get the count of each items from the `result`, like this

    
    
    print result.get("Ba", 0)
    # 9
    print result.get("H", 0)
    # 2
    print result.get("Li", 0)
    # 3
    print result.get("Sa", 0)
    # 0
    

