📌  相关文章
📜  如何检查字符串是否是Python中的有效关键字?

📅  最后修改于: 2022-05-13 01:55:09.098000             🧑  作者: Mango

如何检查字符串是否是Python中的有效关键字?

定义关键字

在编程中,关键字是语言的“保留字”,它向解释器传达特殊含义。它可以是命令或参数。关键字不能用作程序片段中的变量名
Python 中的关键字: Python语言还保留了一些传达特殊含义的关键字。这些知识是学习这门语言的必要部分。以下是Python注册的关键字列表。
错误,elif,lambda,
无,否则,非本地,
真的,除了,不是,
最后,或者,
作为,对于,通过,
断言, 从, 提高,
打破, 全球, 返回,
类,如果,尝试,
继续,导入,同时
def, 在, 与,
del 是, 产量,

如何检查字符串是否关键字?

Python在其语言中定义了一个内置模块“关键字”,它处理与关键字相关的某些操作。函数“ iskeyword() ”检查字符串是否为关键字。如果字符串是关键字,则返回 true,否则返回 false

Python
#Instead of writing this massive Python code
#we can also code this in a different way
 
#Python code to demonstrate working of iskeyword()
 
# importing "keyword" for keyword operations
import keyword
import keyword
# initializing strings for testing while putting them in an array
keys = ["for", "while", "tanisha", "break", "sky",
"elif", "assert", "pulkit", "lambda", "else", "sakshar"]
 
for i in range(len(keys)):
     # checking which are keywords
    if keyword.iskeyword(keys[i]):
        print(keys[i] + " is python keyword")
    else:
        print(keys[i] + " is not a python keyword")


Python
#Python code to demonstrate working of iskeyword()
 
# importing "keyword" for keyword operations
import keyword
 
# printing all keywords at once using "kwlist()"
print ("The list of keywords is : ")
print (keyword.kwlist)


输出:

for is a python keyword
geeksforgeeks is not a python keyword
elif is a python keyword
elseif is not a python keyword
nikhil is not a python keyword
assert is a python keyword
shambhavi is not a python keyword
True is a python keyword
False is a python keyword
akshat is not a python keyword
akash is not a python keyword
break is a python keyword
ashty is not a python keyword
lambda is a python keyword
suman is not a python keyword
try is a python keyword
vaishnavi is not a python keyword

如何打印所有关键字的列表

有时,在分配变量名称时记住所有关键字可能是一项艰巨的任务。因此,在“keyword”模块中提供了一个函数“ kwlist() ”,它打印了所有 33 个Python关键字

Python

#Python code to demonstrate working of iskeyword()
 
# importing "keyword" for keyword operations
import keyword
 
# printing all keywords at once using "kwlist()"
print ("The list of keywords is : ")
print (keyword.kwlist)

输出:

The list of keywords is : 
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 
'try', 'while', 'with', 'yield']


下一篇:

  • Python中的关键字|设置 1
  • Python中的关键字|设置 2