I am trying to create a function (in Python) that takes its contribution (chemical formula) and breaks down into a list. For example, if the input was "HC2H3O2", it would turn it into:
molecule_list = ['H', 1, 'C', 2, 'H', 3, 'O', 2]
This works well so far, but if I put in an element with two letters, for example sodium (Na), it would split it into:
['N', 'a']
I am looking for a way to get my function to scan a string for keys found in a dictionary called elements. I am also considering using regex for this, but I'm not sure how to implement it. This is my function right now:
def split_molecule(inputted_molecule):
"""Take the input and split it into a list
eg: C02 => ['C', 1, 'O', 2]
"""
molecule_list = list(inputted_molecule)
max_length_of_molecule_list = 2*len(molecule_list)
for i in range(0, max_length_of_molecule_list):
try:
if (molecule_list[i] in elements) and (molecule_list[i+1] in elements):
molecule_list.insert(i+1, "1")
except IndexError:
break
if (molecule_list[-1] in elements):
molecule_list.append("1")
for i in range(0, len(molecule_list)):
if molecule_list[i].isdigit():
molecule_list[i] = int(molecule_list[i])
return molecule_list
source
share