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

定义关键字

null

在编程中,关键字是“ 保留字 “通过所传达的语言 对口译员的特殊意义 。它可能是命令或参数。关键词 不能用作变量名 在程序片段中。 Python中的关键字: Python语言还保留了一些传达特殊含义的关键字。这些知识是学习这门语言的必要部分。下面是python注册的关键字列表。 错,伊莱夫,兰姆达, 没有,其他,非本地, 是的,除了,不是, 最后,或者, 作为,作为,通过, 断言,提出, 突破,全球,回归, 同学们,如果,试试看, 继续,导入,同时 def,in,with, 戴尔是,屈服,

如何检查字符串是否正确 A. 关键词?

Python在其语言中定义了一个内置模块“ 关键词 “它处理与关键字相关的某些操作。“功能” iskeyword() “检查字符串是否为关键字。退换商品 如果字符串是 关键字,否则返回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" )


输出:

for is a python keywordgeeksforgeeks is not a python keywordelif is a python keywordelseif is not a python keywordnikhil is not a python keywordassert is a python keywordshambhavi is not a python keywordTrue is a python keywordFalse is a python keywordakshat is not a python keywordakash is not a python keywordbreak is a python keywordashty is not a python keywordlambda is a python keywordsuman is not a python keywordtry is a python keywordvaishnavi is not a python 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']

下一篇文章:

本文由 曼吉特·辛格(S.Nandini) .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享