Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to ascii using ord()

Tags:

python

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:   
      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     
like image 917
suffa Avatar asked Apr 13 '11 21:04

suffa


3 Answers

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)
like image 114
yan Avatar answered Sep 20 '22 17:09

yan


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'
like image 40
Tim Pietzcker Avatar answered Sep 16 '22 17:09

Tim Pietzcker


print "ASCII value: ",  ", ".join(str(i) for i in new_list)
like image 21
sverre Avatar answered Sep 16 '22 17:09

sverre