2015-09-12 14 views
1

當我編碼時,我從列表中選擇一個隨機值並將其與兩個數字並列打印以得出總和。但是,列表中的值仍然顯示引號,我不明白爲什麼。該代碼是:列表中的運算符在打印時仍顯示引號(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

您正在打印生成此格式的列表。爲了得到你想要的輸出,你可以用一個空的分隔符join名單:

print (''.join(sum1)) 

編輯:

只注意到你有操作數爲整數,而不是字符串。要使用這種技術,您應該將所有元素轉換爲字符串。例如:

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

我嘗試添加這並給出了以下錯誤消息:類型錯誤:序列項0:預期str實例,int發現 –

+0

@DaisyBradbury我想我剛剛發現了這個問題。請參閱我的編輯。 – Mureinik

+0

我無法使用此方法,因爲我需要將值保留爲整數,因爲我將其用於稍後在程序中進行計算。 –

1

鑑於你知道的格式,你可以使用打印用格式說明:

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