Python String isidentifier() Method – Tutorial with Examples

Python String isidentifier() Method

The isidentifier() method is a built-in method in Python that checks whether a given string is a valid Python identifier or not. In Python, an identifier is a name given to an entity such as a variable, function, class, etc.

Syntax

The syntax of the isidentifier() method is as follows:

string.isidentifier()

Here, string is the string that we want to check for identifier validity.

Return Value

The isidentifier() method returns True if the string is a valid identifier in Python, otherwise it returns False.

Examples

Here are three different examples of how to use the isidentifier() method in Python:

Example 1: Checking if a String is a Valid Identifier

The following example demonstrates how to use the isidentifier() method to check if a given string is a valid identifier in Python:

string = "my_variable"
result = string.isidentifier()
print(result)

Output:

True

In this example, we define a string “my_variable” and use the isidentifier() method to check whether it is a valid Python identifier. Since the string contains only alphabets and an underscore character, which are valid characters for an identifier, the method returns True.

Example 2: Checking if a String is not a Valid Identifier

The following example demonstrates how to use the isidentifier() method to check if a given string is not a valid identifier in Python:

string = "1234"
result = string.isidentifier()
print(result)

Output:

False

In this example, we define a string “1234” and use the isidentifier() method to check whether it is a valid Python identifier. Since the string starts with a digit, which is not a valid character for an identifier, the method returns False.

Example 3: Checking if a String is a Keyword

The following example demonstrates how to use the isidentifier() method to check if a given string is a Python keyword:

import keyword

string = "if"
result = string.isidentifier() and not keyword.iskeyword(string)
print(result)

Output:

False

In this example, we define a string “if” and use the isidentifier() method to check whether it is a valid Python identifier. Since “if” is a Python keyword and not a valid identifier, the method returns False. We also use the iskeyword() method from the built-in keyword module to check if the string is a Python keyword.

Use Cases

The isidentifier() method can be useful in a variety of scenarios, such as:

  • Validating user input to ensure that it only contains valid Python identifiers
  • Checking if a given string is a valid identifier before using it as a variable name, function name, or class name
  • Preventing the use of reserved words or keywords as identifier names in Python code

Leave a Reply

Your email address will not be published. Required fields are marked *