Can I calculate the molecular mass from a formula like this C9H15N4O8P with Python e.g. using rdkit? I think rdkit.Chem.Descriptors.MolWt needs a molecule object. Though, to generate that I would need e.g. a SMILES string. Is there any other python module that can do the trick?

I found this: http://verahill.blogspot.com/2012/10/molecular-weight-calculator-in-python.html


2 Answers 2


I tried to adapt this approach within rdKit to calculate exact mass (for mass spectrometry), but was not successful.

This library (https://pypi.org/project/molmass/) appears to be able to do this:

from molmass import Formula
f = Formula('C7H11N3O2')

As you mentioned, rdKit does not accept a chemical formula as input. The main reason for this are probably isomers. You could however use rdKit to initiate all the atoms, get their mass and add them together.

import re
from rdkit import Chem

def get_mass(formula):

    parts = re.findall("[A-Z][a-z]?|[0-9]+", formula)
    mass = 0

    for index in range(len(parts)):
        if parts[index].isnumeric():

        atom = Chem.Atom(parts[index])
        multiplier = int(parts[index + 1]) if len(parts) > index + 1 and parts[index + 1].isnumeric() else 1
        mass += atom.GetMass() * multiplier

    return mass


>>> get_mass("C9H15N4O8P")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.