使用关键字模块检查给定的字符串是否是关键字

在该程序中,用户将给出一个字符串,我们必须检查它是否是Python中的关键字。为了在Python中执行此任务,我们将使用一个名称为关键字的模块。在执行此任务之前,我们将看到一个程序,该程序将返回Python编程语言的所有关键字。

Python程序打印所有关键字

# importing the module
import keyword

#获取所有关键字的列表
List_of_key=keyword.kwlist

#打印关键字的数量
print("No of keyword in Python: ",len(List_of_key))

#打印所有python中存在的关键字列表。
print("List of keyword:",List_of_key)

输出结果

No of keyword in Python:  33
List of keyword: ['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语言中的total关键字为33。

  • Python不允许我们在程序中使用关键字作为变量。

检查给定字符串是否是关键字的算法?

  1. 最初,我们将通过使用import函数将关键字模块包含在Python中。

  2. 从用户那里获取输入字符串。

  3. 通过使用获取变量中所有关键字列表kwlist()从模块关键字的功能

  4. 使用Python的关键字检查给定的字符串是否在上面创建的列表中。

    1. 如果位于列表中,则打印给定的字符串是Python编程语言中的关键字。

    2. 如果它不在列表中,则打印给定的字符串不是Python编程语言中的关键字。

因此,让我们开始通过上述算法的实现来编写python程序,

检查给定字符串是否为关键字的Python程序

# importing the module
import keyword

#输入字符串
str=input("Enter a string: ")

#获取所有关键字的列表
List_of_key=keyword.kwlist

# 检查给定字符串是否为关键字
if str in List_of_key:
    print("String {} is a keyword.".format(str))
else:
    print("String {} is not a keyword.".format(str))

输出结果

RUN 1:
Enter a string: nhooo
String nhooo is not a keyword.

RUN 2:
Enter a string: try
String try is a keyword.

RUN 3:
Enter a string: nonlocal
String nonlocal is a keyword.