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

时间:2015-09-12 17:08:26

标签: 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 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

这些数字也随机生成,但工作正常。有谁知道如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您正在打印生成此格式的列表。为了得到您想要的输出,您可以使用空分隔符join列表:

print (''.join(sum1))

编辑:

注意到你的操作数是int,而不是字符串。要使用此技术,您应该将所有元素转换为字符串。 E.g:

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

答案 1 :(得分:1)

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

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