2017-10-18 121 views
0

我需要有計算後的百分比符號,我怎樣才能改變這種代碼,以便將錯誤:添加字符串到整數

TypeError: unsupported operand type(s) for +: 'int' and 'str' 

不顯示。要刪除小數點,計算爲'int'。

global score 
score = 2 

def test(score): 
    percentage = int(((score)/5)*100) + ("%") 
    print (percentage) 

test(score) 
+1

投下你的號碼爲字符串。 –

+0

你*仍*需要將數字*返回*轉換爲str。 – Mangohero1

回答

5

使用字符串格式化:

print('{:.0%}'.format(score/5)) 
0

由於錯誤說,你不能申請一個int和一個字符串之間的+操作。你可以,但是,INT自己轉換爲字符串:

percentage = str(int(((score)/5)*100)) + ("%") 
# Here ------^ 
0

使用此

global score 
score = 2 

def test(score): 
    percentage = str(int(((score)/5)*100)) + "%" 
    print (percentage) 

test(score) 
1

在蟒蛇(和許多其他語言)中,+運營商有兩個目的。它可以用來獲得兩個數字(數字+數字)的總和,或連接字符串(字符串+字符串)。在這種情況下,python無法決定+應該做什麼,因爲其中一個操作數是一個數字,另一個是字符串。

要解決這個問題,你必須改變一個操作數來匹配另一個操作數的類型。在這種情況下,你唯一的選擇就是讓數字轉換成字符串(使用內置str()功能很容易做到:

str(int(((score)/5)*100)) + "%" 

或者,你可以完全拋棄+與語法格式去

舊語法:

"%d%%" % int(((score)/5)*100) 

新語法:

'{}%'.format(int(((score)/5)*100)) 
0

對於Python> = 3.6:

percentage = f"{(score/5) * 100}%" 
print(percentage)