我必须先说这是一个新手(学习),所以请放弃对一个对你的世界有限的人(Python)的明显的疏忽。
我的目标是从用户获取字符串并将其转换为Hex和Ascii字符串。我能够使用hex(encode("hex")
)成功完成此操作,但ascii却不是这样。我找到了ord()
方法并尝试使用它,如果我只使用:print ord(i)
,循环将遍历并将值垂直打印到屏幕上,而不是我想要的位置。所以,我试图用一个字符串数组捕获它们,这样我就可以将它们连接到一行字符串,在'Hex'值下水平打印它们。我只是用尽了我的资源来搞清楚......任何帮助都是谢谢。谢谢!
while True:
stringName = raw_input("Convert string to hex & ascii(type stop to quit): ")
if stringName == 'stop':
break
else:
convertedVal = stringName.encode("hex")
new_list = []
convertedVal.strip() #converts string into char
for i in convertedVal:
new_list = ord(i)
print "Hex value: " + convertedVal
print "Ascii value: " + new_list
答案 0 :(得分:6)
这是你要找的吗?
while True:
stringName = raw_input("Convert string to hex & ascii(type stop to quit): ").strip()
if stringName == 'stop':
break
print "Hex value: ", stringName.encode('hex')
print "ASCII value: ", ', '.join(str(ord(c)) for c in stringName)
答案 1 :(得分:3)
这样的东西?
def convert_to_ascii(text):
return " ".join(str(ord(char)) for char in text)
这会给你
>>> convert_to_ascii("hello")
'104 101 108 108 111'
答案 2 :(得分:1)
print "ASCII value: ", ", ".join(str(i) for i in new_list)