I must preface this by saying that I am a neophyte (learning), so please waive the omission of the obvious in deference to a man who has had limited exposure to your world (Python).
My objective is to get string from a user and convert it to Hex and Ascii string. I was able to accomplish this successfully with hex (encode("hex")
), but not so with ascii. I found the ord()
method and attempted to use that, and if I just use: print ord(i)
, the loop iterates the through and prints the values to the screen vertically, not where I want them. So, I attempted to capture them with a string array so I can concat them to a line of string, printing them horizontally under the 'Hex" value. I've just about exhausted my resources on figuring this out ... any help is appreciated. Thanks!
while True:
stringName = raw_input("Convert string to hex & ascii(type stop to quit): ")
if stringName == 'stop':
break
else:
con开发者_如何学GovertedVal = 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
Is this what you're looking for?
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)
Something like this?
def convert_to_ascii(text):
return " ".join(str(ord(char)) for char in text)
This gives you
>>> convert_to_ascii("hello")
'104 101 108 108 111'
print "ASCII value: ", ", ".join(str(i) for i in new_list)
精彩评论