将字符串添加到整数

时间:2017-10-18 20:19:57

标签: python string python-3.x integer percentage

我需要在计算后得到百分号,如何更改此代码以便错误:

10-18 15:27:17.570 22426-22426/cliu.tutorialcrypto E/AsymmetricAlgorithmRSA: Public key: OpenSSLRSAPublicKey{modulus=c1312eb5c24da9577dd40263cec233b8be40ed227b81df3c442363f1dfd5364e9e2ba96d4dd7c1011d2633d6603beb1a483b75b8af8a87b10ebe918729b6afe95893d5c93b3f99727785110f2373d20ced8bfe2421c9c682ee737c60a7c6199be3d2e7e4687d69cedc50965b8cebc4445cdfe7a13a7df5eda6a6d4304d057505,publicExponent=10001}
10-18 15:27:17.570 22426-22426/cliu.tutorialcrypto E/AsymmetricAlgorithmRSA: Private key: OpenSSLRSAPrivateCrtKey{modulus=c1312eb5c24da9577dd40263cec233b8be40ed227b81df3c442363f1dfd5364e9e2ba96d4dd7c1011d2633d6603beb1a483b75b8af8a87b10ebe918729b6afe95893d5c93b3f99727785110f2373d20ced8bfe2421c9c682ee737c60a7c6199be3d2e7e4687d69cedc50965b8cebc4445cdfe7a13a7df5eda6a6d4304d057505,publicExponent=10001}

不显示。要删除小数点,计算是' int'。

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

6 个答案:

答案 0 :(得分:5)

使用字符串格式:

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

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

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

或者,您可以完全抛弃+并使用格式语法。

旧语法:

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

新语法:

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

使用此

global score
score = 2

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

test(score)

答案 5 :(得分:0)

对于Python> = 3.6:

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