如何验证字符属于可移植字符集

How to validate character belongs to the portable character set

POSIX个标准参考Portable Character Set.

我需要检查用户输入是否符合标准并且仅包含 acceptable 个字符。有什么方便的检查方法吗?

从维基百科手动移植 table 的方法很繁琐:

portable_set = '[=10=]\a\b...'
def check(sample):
     return all(c in portable_set for c in sample)

但是POSIX就在我们身边,所以我相信在python标准库的某个地方应该已经定义了这样的集合。但是我不知道在哪里可以找到它。

我不相信 python 中内置了这样的集合。如果它确实存在,我希望它驻留在 string 模块中,但它不在那里。

但是,python 是否有 string.printable,我很确定它包含可移植字符集的前三个元素以外的所有元素。您可以通过将其余部分附加到定义上来使您的定义更简洁:

import string

portable_set = set(string.printable + '[=10=]\a\b')
def check(sample):
    return set(sample).issubset(portable_set)

来自 Python 标准库的字符串包含一些字符串常量。其中之一是 string.printable。我想这就是你要找的。

import string
string.printable

您可以在此处阅读有关字符串和其他常量的更多信息:https://docs.python.org/3/library/string.html .