Python String isidentifier()

Python String isidentifier() method

Python String isidentifier() method is used to check if the string is a valid identifier according to Python language.

The rules for a valid identifier in Python language are given in Python Variables tutorial under “Rules for naming a variable” section.

Consider that given string is in x.

x = "value_1"

Then the return value of x.isdecimal() is

True

In this tutorial, you will learn the syntax and usage of String isidentifier() method in Python language.

Syntax of isidentifier() method

The syntax of String isidentifier() method in Python is given below.

str.isidentifier()

Parameters

The string isidentifier() method takes no parameters.

Return value

The string isidentifier() method returns a boolean value of True if the given string value is a valid identifier, otherwise False.

Examples

1. Checking if given string is a valid identifier in Python

In this example, we take a string value "value_1" in variable x. We have to check if this string is a valid identifier.

The string starts with an alphabet, and contains only alphabets, digits, and underscore symbol. The given string is a valid identifier by the rules of naming an identifier in Python. isidentifier() method should return True, and execute if-block.

Python Program

x = "value_1"

if x.isidentifier():
    print('Given string is a valid IDENTIFIER.')
else:
    print('Given string is NOT a valid IDENTIFIER.')
Run Code Copy

Output

Given string is a valid IDENTIFIER.

2. isidentifier() with an invalid identifier name in string in Python

In the following program, we take a string value "1_my_car" in variable x. We have to check if the string is a valid identifier.

The string "1_my_car" starts with a digit, which is against the rules for naming an identifier. Therefore, isidentifier() method should return False, and execute else-block.

Python Program

x = "1_my_car"

if x.isidentifier():
    print('Given string is a valid IDENTIFIER.')
else:
    print('Given string is NOT a valid IDENTIFIER.')
Run Code Copy

Output

Given string is NOT a valid IDENTIFIER.

3. isidentifier() with an empty string

In the following program, we take an empty string value in variable x, and check the return value of isidentifier() for this empty string.

Python Program

x = ""

if x.isidentifier():
    print('Given string is a valid IDENTIFIER.')
else:
    print('Given string is NOT a valid IDENTIFIER.')
Run Code Copy

Output

Given string is NOT a valid IDENTIFIER.

Empty string is never a valid identifier.

Summary

In this tutorial of Python String Methods, we learned about String isidentifier() method, its syntax, and examples.

Related Tutorials

Code copied to clipboard successfully 👍