Python ord() function.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • karthikr_04
    New Member
    • Jul 2006
    • 2

    #1

    Python ord() function.

    Hello ,
    I am new and I was stuck with the ord function.
    When i passed the value like this it gave me proper o/p:
    >>ord('\x16')
    22
    but when i concatenate '\x' and 16 the length of the string becomes 4 and it gives error.What's the method to convert it into ASCII like the one above for a string.
  • ghostdog74
    Recognized Expert Contributor
    • Apr 2006
    • 511

    #2
    Originally posted by karthikr_04
    Hello ,
    I am new and I was stuck with the ord function.
    When i passed the value like this it gave me proper o/p:
    >>ord('\x16')
    22
    but when i concatenate '\x' and 16 the length of the string becomes 4 and it gives error.What's the method to convert it into ASCII like the one above for a string.
    it's hex representation
    eg. you can try ord('a'). It gives you 97. looking at ascii chart, 'a' is hex 61. so if you do ord('\x61'), it will also give you 97.

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      More precisely, "\x" is an escape operator or hex conversion and the number following it is its operand and must be a hex number. If you try:

      >>> b='\x'+'0a'
      ValueError: invalid \x escape

      you may begin to see.

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        If you really need your program to convert a string which represents a hex number, you can use:

        >>> eval("0x0a")
        10

        Comment

        Working...