python - 在 Python 中从 Ascii 转换某些特殊字符时遇到问题

标签 python regex python-2.7 ascii special-characters

我正在尝试用 Python (2.7) 编写一个脚本,这会节省我一些时间并将 Ascii 转换为 Dec 和 hex,反之亦然,但是当输入一个特殊的字符(例如:')作为输入时,它似乎无法将其识别为 Ascii 字母(“isAscii”返回“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)

关于python - 在 Python 中从 Ascii 转换某些特殊字符时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32071573/

相关文章:

Python:如何为一个键分配多个值

python - 是否有计算对数正态均值和方差的 Python 方法?

ruby-on-rails - 测试字符串是否无内容

python - 嵌套树到列表列表转换中以错误格式返回的列表

python-2.7 - 用于访问 CalDAV 服务器的 Python 库

python - python中的{}和[]有什么区别?

python - 在树莓派 3 上使用 V4L2、python 的奇怪结果

macos - Python basemap 导入错误: "requirement already satisfied"

javascript - 电子邮件验证不起作用

JavaScript 正则表达式 : give me everything except what is between this pattern