在Python 2.7中将int ordinal附加到str

时间:2017-06-27 13:15:15

标签: python-2.7

如何在Python 2.7中将包含序数的int附加到str? 例如:

number = 10 # You can assume its smaller than 128
mystr = "abc"

mystr = mystr+number # Gives error
assert mystr == "abc\x0A"

当然,“mystr%d”%number或mystr + str(number)不起作用,他们会给出“abc10”

2 个答案:

答案 0 :(得分:2)

import struct
mystr = mystr+struct.pack("b",number)

满足断言。

答案 1 :(得分:2)

我认为您需要内置函数chr

number = 10 
mystr = "abc"

mystr = mystr + chr(number)