如何将自定义列表作为 python 中的输出?
How do I get customized list as a output in python?
我有这个代码。
character = input("Enter a character: \n")
def ASCIItoHEX(ascii):
hexa = []
for i in range(len(ascii)):
ch = ascii[i]
in1 = ord(ch)
part = hex(in1)
hexa += part
return hexa
if __name__ == '__main__':
hexadecimal = ASCIItoHEX(character)
print(hexadecimal)
当我输入“1111”时,它会给我这样的输出:
['0', 'x', '3', '1', '0', 'x', '3', '1', '0', 'x', '3', '1', '0', 'x', '3', '1']
但我想要这样的输出:
['0x31', '0x31', '0x31', '0x31']
如何获得这个输出?
使用 list.append()
而不是 +=
来追加整个字符串。否则字符串将被视为序列并拆分为字符。
character = input("Enter a character: \n")
def ASCIItoHEX(ascii):
hexa = []
for i in range(len(ascii)):
ch = ascii[i]
in1 = ord(ch)
part = hex(in1)
hexa.append(part)
return hexa
if __name__ == '__main__':
hexadecimal = ASCIItoHEX(character)
print(hexadecimal)
另一种方式是
hexa += [part]
连接两个列表。
我有这个代码。
character = input("Enter a character: \n")
def ASCIItoHEX(ascii):
hexa = []
for i in range(len(ascii)):
ch = ascii[i]
in1 = ord(ch)
part = hex(in1)
hexa += part
return hexa
if __name__ == '__main__':
hexadecimal = ASCIItoHEX(character)
print(hexadecimal)
当我输入“1111”时,它会给我这样的输出:
['0', 'x', '3', '1', '0', 'x', '3', '1', '0', 'x', '3', '1', '0', 'x', '3', '1']
但我想要这样的输出:
['0x31', '0x31', '0x31', '0x31']
如何获得这个输出?
使用 list.append()
而不是 +=
来追加整个字符串。否则字符串将被视为序列并拆分为字符。
character = input("Enter a character: \n")
def ASCIItoHEX(ascii):
hexa = []
for i in range(len(ascii)):
ch = ascii[i]
in1 = ord(ch)
part = hex(in1)
hexa.append(part)
return hexa
if __name__ == '__main__':
hexadecimal = ASCIItoHEX(character)
print(hexadecimal)
另一种方式是
hexa += [part]
连接两个列表。