2017-10-18 71 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)