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
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 = "")
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.