【问题标题】:Adding string to integer将字符串添加到整数
【发布时间】:2017-10-18 20:19:56
【问题描述】:
计算后我需要百分号,我该如何更改此代码,所以错误:
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)
【问题讨论】:
标签:
python
string
python-3.x
integer
percentage
【解决方案1】:
使用字符串格式:
print('{:.0%}'.format(score/5))
【解决方案2】:
试试str(int(((score)/5)*100)) + ("%")
【解决方案3】:
在 python(和许多其他语言)中,+ 运算符具有双重用途。它可用于获取两个数字的总和(数字 + 数字),或连接字符串(字符串 + 字符串)。在这种情况下,python 无法决定 + 应该做什么,因为您的操作数之一是数字,另一个是字符串。
要解决此问题,您必须更改一个操作数以匹配另一个操作数的类型。在这种情况下,您唯一的选择是将数字变成一个字符串(使用内置的str() 函数很容易做到:
str(int(((score)/5)*100)) + "%"
或者,您可以完全放弃 + 并使用格式语法。
旧语法:
"%d%%" % int(((score)/5)*100)
新语法:
'{}%'.format(int(((score)/5)*100))
【解决方案4】:
正如错误所说,您不能在 int 和字符串之间应用 + 运算符。但是,您可以自己将 int 转换为字符串:
percentage = str(int(((score)/5)*100)) + ("%")
# Here ------^
【解决方案5】:
使用这个
global score
score = 2
def test(score):
percentage = str(int(((score)/5)*100)) + "%"
print (percentage)
test(score)
【解决方案6】:
对于 Python >= 3.6:
percentage = f"{(score / 5) * 100}%"
print(percentage)