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

列表中的运算符在打印时仍显示引号(Python 3.1),python,python-3.x,operators,python-3.1,Python,Python 3.x,Operators,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 operato

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

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

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

您正在打印一个列表,该列表生成这种格式。为了获得所需的输出,您可以使用空分隔符加入列表:

print (''.join(sum1))
编辑:

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

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

如果您知道格式,您可以使用带有格式说明符的print:

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

我尝试添加此项,但收到以下错误消息:TypeError:sequence item 0:expected str instance,intfound@DaisyBradbury我想我刚刚发现了问题。请查看我的编辑。我不能使用此方法,因为我需要将值保留为整数,因为我以后在程序中使用它进行计算。@DaisyBradbury您只是为了打印而转换它们。事实上,我们正在打印基于
sum1
的列表理解,而不是修改
sum1
本身。这似乎不必要地复杂。