Python 使用ord()将字符串转换为ascii
在这之前,我必须说我是一个新手(学习),所以请不要忽略显而易见的东西,以尊重一个对你的世界(Python)接触有限的人 我的目标是从用户处获取字符串,并将其转换为十六进制和Ascii字符串。我能够用hex(Python 使用ord()将字符串转换为ascii,python,Python,在这之前,我必须说我是一个新手(学习),所以请不要忽略显而易见的东西,以尊重一个对你的世界(Python)接触有限的人 我的目标是从用户处获取字符串,并将其转换为十六进制和Ascii字符串。我能够用hex(encode(“hex”))成功地实现这一点,但用ascii就不行了。我找到了ord()方法并尝试使用它,如果我只使用:print ord(I),循环将遍历并将值垂直打印到屏幕上,而不是我想要的位置。所以,我尝试用字符串数组捕获它们,这样我就可以将它们浓缩成一行字符串,在“十六进制”值下水平打
encode(“hex”)
)成功地实现这一点,但用ascii就不行了。我找到了ord()
方法并尝试使用它,如果我只使用:print ord(I)
,循环将遍历并将值垂直打印到屏幕上,而不是我想要的位置。所以,我尝试用字符串数组捕获它们,这样我就可以将它们浓缩成一行字符串,在“十六进制”值下水平打印它们。我已经用尽了我的资源来解决这个问题……非常感谢您的帮助。谢谢
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
像这样的
def convert_to_ascii(text):
return " ".join(str(ord(char)) for char in text)
这给你
>>> convert_to_ascii("hello")
'104 101 108 108 111'
这就是你要找的吗
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)
您希望ASCII输出是什么样子的?只是逗号分隔的十进制值?例如:“97,98,65,65如果用户输入字符串:“123431”:十六进制=313233343331 ascii=49 50 51 51 49感谢DP。。。。另外,我不是想在我最后一条评论的ascii值之间加空格。是的!我的代码和之前的代码几乎相同,但是切换了!为什么在stringName上使用.strip()。。。线路?再次感谢!
print "ASCII value: ", ", ".join(str(i) for i in new_list)