在Python中,要判断一个字符串是否是保留字,可以使用 `keyword` 模块的 `iskeyword()` 方法。以下是如何使用该方法的示例:
import keyword
检查字符串是否为保留字
if keyword.iskeyword("def"):
print("def 是保留字")
else:
print("def 不是保留字")
if keyword.iskeyword("hello"):
print("hello 不是保留字")
else:
print("hello 不是保留字")
执行上述代码,输出将会是:
def 是保留字
hello 不是保留字
请注意,Python保留字是区分大小写的,因此 `True` 和 `true` 被视为不同的单词。