无法从 Python 中的 Ascii 转换某些特殊字符

Trouble converting certain special characters from Ascii in Python

我正在尝试在 Python (2.7) 中编写一个脚本,这将节省我一些时间并将 Ascii 转换为 Dec 和 hex,反之亦然,但是当输入一个特殊的字符时(例如:') 作为输入,似乎无法将其识别为 Ascii 字母 ("isAscii" returns "False")。 我找不到合适的解决方案(我考虑过正则表达式,但我不确定),想知道是否有人可以给我一些指导?

我的代码:

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()

非常感谢!

我认为这仅仅是因为 string.ascii_letters 只是字母(而不是所有字符)。所以像 ' 这样的字符将不会被视为有效:

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

编辑: 这是@Maayan 找到的解决此问题的解决方案是使用:

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

使用 "return all(ord(c) < 128 for c in s)" 解决了它,以检查输入是否为 ascii 而不是 "Ascii.letters"(正如你向我指出的,不包括非字母的字符)。 谢谢你的帮助! :)