0
moleculeparse = chemparse.parse_formula(molecule) #Parses the molecular formula to present the atoms and No. of atoms. Molecule here is 'C2H6O2' 
print(moleculeparse) #Print the dictionary

for x,y in moleculeparse.items(): #For every key and value in dictionary
    y = numpy.random.randint(0,y+1) #Randomly generate the value between 0 and y+1
    if y == 0:
        continue
    else:
        y = str(y)
        print(x+y, end = "")

The above code essentially parses 'C2H6O' and puts it into a dictionary. Then for every key and value in the dictionary, the value is randomly generated.

When running this code, an example of an output can be something such as 'C1H4', this is what the print statement in the last line does. I want to be able to assign this output to a variable for later use but I'm not sure how to do this. I've assigned tried a = x+y, end = "" but this leads to an error. Any help would be appreciated

Jak
  • 3
  • 1

2 Answers2

1

This should be right

moleculeparse = chemparse.parse_formula(molecule) #Parses the molecular formula to present the atoms and No. of atoms. Molecule here is 'C2H6O2' 
print(moleculeparse) #Print the dictionary

for x,y in moleculeparse.items(): #For every key and value in dictionary
    y = numpy.random.randint(0,y+1) #Randomly generate the value between 0 and y+1
    if y == 0:
        continue
    else:
        y = str(y)
        a = x+y
        print(a, end = "")
Alik.Koldobsky
  • 334
  • 1
  • 10
  • The point of the `print(x+y, end = "")` is to get everything to print in one line. The output of that print statement is what I want assigned to a variable as I need to use it later. This solution unfortunatley doesn't help later on as I use a module that needs to work directly with the string and the 'end = ""' is causing problems hence why I wanted to assign the whole output to one variable – Jak Jan 18 '22 at 11:13
0

The easiest approach is to save each result in a list and then collate it into a string. You do not want to "assign the print output to a variable": there is no need to print each result.

moleculeparse = chemparse.parse_formula(molecule) #Parses the molecular formula to present the atoms and No. of atoms. Molecule here is 'C2H6O2' 
print(moleculeparse) #Print the dictionary

all_results = []

for x, y in moleculeparse.items():  # For every key in dictionary
    y = numpy.random.randint(0,y+1)  # Randomly generate the value between 0 and y+1
    if y == 0:
        continue
    else:
        y = str(y)
        all_results.append(x+y)
in_one_line = "".join(all_results)
print(in_one_line)
azelcer
  • 1,383
  • 1
  • 3
  • 7
  • Thank you very much. I actually solved this problem a few days ago and used this solution almost word for word! – Jak Jan 28 '22 at 15:12