列表中的运算符在打印时仍显示引号 (Python 3.1)

Operators from list is still showing quotation marks when printed (Python 3.1)

当我编码时,我从列表中选择一个随机值并将其与两个数字一起打印以求和。但是,列表中的值仍然显示引号,我不明白为什么。代码是:

import random
level = input('Please choose either easy, medium or hard')
if level == 'easy':
    num1 = random.randint(1,5)
    num2 = random.randint(1,5)
    #Chooses a random operator from the list
    op = random.choice(['+', '-', '*'])
    #Arranges it so the larger number is printed first
    if num1 > num2:
        sum1 = (num1, op, num2)
    else:
        sum1 = (num2, op, num1)
    #Prints the two numbers and the random operator
    print(sum1)

我尝试 运行 这段代码,得到的结果是:

(4, '*', 3)

当我希望它显示为:

4*3

这些数字也是随机生成的,但效果很好。有谁知道如何解决这个问题?

您正在打印一个列表,它会生成这种格式。为了获得所需的输出,您可以 join 带有空分隔符的列表:

print (''.join(sum1))

编辑:

刚刚注意到您的操作数是整数,而不是字符串。要使用此技术,您应该将所有元素转换为字符串。例如:

print (''.join([str(s) for s in sum1]))

如果你知道格式,你可以使用带有格式说明符的打印:

>>> sum1 = (4, '*', 3)
>>> print("{}{}{}".format(*sum1))
4*3