Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

keyword
python
communitycreator

What is keyword.iskeyword() in Python?

Eman Kashif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

Python is a high-level programming language that provides functionalities for several operations. The keyword module comes with various methods to manipulate keywords.

The function keyword.iskeyword() checks if a string is a valid keyword in Python.

Syntax

keyword.iskeyword(x)

Parameters

  • x: This is the specified string that is passed as a parameter to check if it is a valid keyword or not. This parameter is required.

Return value

This function returns the Boolean value True if x is a valid keyword. Otherwise, it returns False.

Example

#import module
import keyword

#intialize test strings
string1 = 'import'
string2 = 'no'
string3 = 'from'
string4 = 'val'
string5= 'as'

#check for valid keywords
print(string1,': ',keyword.iskeyword(string1))
print(string2,': ',keyword.iskeyword(string2))
print(string3,': ',keyword.iskeyword(string3))
print(string4,': ',keyword.iskeyword(string4))
print(string5,': ',keyword.iskeyword(string5))
Implementing the keyword.iskeyword()

Explanation

  • Line 2: We import the keyword module.
  • Lines 5 to 9: We initialize test strings. Some are reserved keywords in Python.
  • Lines 12 to 16: We test to see whether the strings are valid keywords or not.

In the output, the test string is first printed. True is printed if it is a valid keyword. Otherwise, False is printed.

RELATED TAGS

keyword
python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring