我必须先说这是一个新手(学习),所以请放弃对一个对你的世界有限的人(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
Run Code Online (Sandbox Code Playgroud)
这是你在找什么?
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)
Run Code Online (Sandbox Code Playgroud)
像这样吗
def convert_to_ascii(text):
return " ".join(str(ord(char)) for char in text)
Run Code Online (Sandbox Code Playgroud)
这给你
>>> convert_to_ascii("hello")
'104 101 108 108 111'
Run Code Online (Sandbox Code Playgroud)