MSH
MSH

Reputation: 163

Trouble converting certain special characters from Ascii in Python

I'm trying to write a script in Python (2.7) which would save me some time and convert Ascii to Dec and hex and the other way around, but when entering a special char (for example:') as input, it seems not to recognize it as Ascii letter ("isAscii" returns "False"). I could not find a proper solution (I thought about regex, but I'm not sure), and was wondering if someone may offer me some direction?

my code:

import struct
import string
import re

def isAscii(s):
    for c in s:
        if c not in string.ascii_letters:
            return False
    return True

is_hex = re.compile(
         r'^[+\-]?'                    
          '0'                           
          '[xX]'                        
          '(0|'                         
          '([1-9A-Fa-f][0-9A-Fa-f]*))$' 
).match

End='0'
while (End!='1'):
        print("Please enter your input:")
        num = raw_input()
        num = num.split(',')
        for i in range (0,len(num)):
                if isAscii(num[i]):
                    print("Decimal: %d, Hex: %s") %(ord(str(num[i])) ,hex(ord(str(num[i]))))
                elif is_hex(num[i]):
                     print("Decimal: %d, Chr: %s") %(ord((chr(int(num[i], 16)))) ,(chr(int(num[i], 16))))

                else:
                    print("Hex: %s, Chr: %s") % (hex(int(num[i])) ,(chr(int(num[i]))))
        print("Press any key to continue OR Press 1 to exit")
        End = raw_input()

Thanks a lot!

Upvotes: 1

Views: 428

Answers (2)

Challensois
Challensois

Reputation: 542

I think it is simply due to the fact that string.ascii_letters are only the letters (and not all the characters).. So a character like ' will not be considered as valid:

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

EDIT: Here is the solution found by @Maayan to overcome this issue is to use:

def isAscii(s):
    return all(ord(c) < 128 for c in s)

Upvotes: 2

MSH
MSH

Reputation: 163

Solved it using "return all(ord(c) < 128 for c in s)" in order to check if the input is ascii instead of "Ascii.letters" (which as you pointed out to me, does not include chars that are not letters). Thanks for your help! :)

Upvotes: 2

Related Questions