Python 将字符串添加到整数

Python 将字符串添加到整数,python,string,python-3.x,integer,percentage,Python,String,Python 3.x,Integer,Percentage,我需要在计算后使用百分号,如何更改此代码以避免错误: 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) 使用字符串格式: print('

我需要在计算后使用百分号,如何更改此代码以避免错误:

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)
使用字符串格式:

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

请尝试
str(int(((score)/5)*100))+(“%”

正如错误所述,您不能在int和字符串之间应用
+
运算符。但是,您可以自己将int转换为字符串:

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

global score
score = 2

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

test(score)
在python(以及许多其他语言)中,
+
操作符具有双重用途。它可用于获取两个数字的总和(数字+数字),或连接字符串(字符串+字符串)。在这种情况下,python无法决定
+
应该做什么,因为一个操作数是数字,另一个是字符串

要解决此问题,必须更改一个操作数以匹配另一个操作数的类型。在这种情况下,您唯一的选择是将数字转换为字符串(使用内置函数可轻松完成:

str(int(((score)/5)*100)) + "%"
或者,您可以完全抛弃
+
,使用格式语法

旧语法:

"%d%%" % int(((score)/5)*100)
'{}%'.format(int(((score)/5)*100))
新语法:

"%d%%" % int(((score)/5)*100)
'{}%'.format(int(((score)/5)*100))
对于Python>=3.6:

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

将数字转换为字符串。您仍然需要将数字转换回str。