如何检查字符串是否是有效的python标识符?包括关键字检查?
有谁知道是否有任何内置的python方法将检查某些东西是否是有效的python变量名,其中包括对保留关键字的检查?(因此,例如“ in”或“
for”之类的操作会失败…)
失败了,有人知道我在哪里可以获得保留关键字的列表(即,从python内部动态生成,而不是从在线文档中复制粘贴内容)吗?或者,还有另一种写支票的好方法吗?
令人惊讶的是,通过将setattr包装在try / except中进行的测试不起作用,如下所示:
setattr(myObj, 'My Sweet Name!', 23)
…确实有效!(…甚至可以使用getattr检索!)
-
该
keyword
模块包含所有保留关键字的列表:>>> import keyword >>> keyword.iskeyword("in") True >>> keyword.kwlist ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
请注意,随着关键字列表的更改(尤其是在Python 2和Python 3之间),此列表将根据所使用的Python的主要版本而有所不同。
如果还需要所有内置名称,请使用
__builtins__
>>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
并请注意,其中一些(如
copyright
)实际上并没有什么大不了的。还有一个警告:请注意,在Python 2
True
,False
和None
不被视为关键字。但是,分配给None
是SyntaxError。分配给True
或被False
允许,尽管不建议这样做(与任何其他内置函数相同)。在Python
3中,它们是关键字,因此这不是问题。
-
如何在 Python 中检查字符串是否是有效的 JSON?
2022-05-26 关注 0 浏览12 1答案
-
如何在Python中检查字符串是否为有效的JSON?
2021-01-31 关注 0 浏览101 1答案
-
如何检查字符串是否为有效数字?
2022-03-22 关注 1 浏览40 1答案
-
如何检查字符串是否是有效的 HTTP URL?
2022-04-11 关注 0 浏览19 1答案
-
Python-如何检查字符串是否为空?
2021-02-02 关注 0 浏览85 1答案
-
如何检查字符串是否包含某些字符串
2021-02-02 关注 0 浏览154 1答案
-
如何检查字符串是否为有效的HTTP URL?
2021-02-02 关注 0 浏览100 1答案
-
如何检查字符串是否包含'+'字符
2021-01-30 关注 0 浏览101 1答案
-
在Python中,如何检查字符串是否仅包含某些字符?
2021-01-29 关注 0 浏览93 1答案
-
如何检查字符串是否包含 Python 列表中的元素
2022-04-11 关注 0 浏览25 1答案