如何在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”
答案 0 :(得分:2)
import struct
mystr = mystr+struct.pack("b",number)
满足断言。
答案 1 :(得分:2)
我认为您需要内置函数chr
:
number = 10
mystr = "abc"
mystr = mystr + chr(number)