如何将打印输出分配给变量

How to assign print output to a variable

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 = "")

上面的代码实质上是解析了'C2H6O',并将其放入字典中。然后对于字典中的每个键和值,随机生成值。

当运行此代码时,输​​出的示例可以是'C1H4'之类的东西,这就是最后一行中的打印语句所做的。我希望能够将此输出分配给一个变量供以后使用,但我不确定如何执行此操作。我已分配 tried a = x+y, end = "" 但这会导致错误。任何帮助将不胜感激

这个应该没错

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 = "")

最简单的方法是将每个结果保存在一个列表中,然后将其整理成一个字符串。您不想“将打印输出分配给变量”:不需要打印每个结果。

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)