What is the string.isidentifier() method in Python?

The Python isidentifier() method checks if a string is a valid identifier or not.

Syntax

string.isidentifier()

Return value

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

Rules for a valid identifier

In Python, a valid identifier should start with a letter in the alphabet (a-z or A-Z) or an underscore (_), followed by zero, more letters, numbers (0-9), or underscores. The identifier should not be a Python keywordReserved identifier that has special meaning, e.g., break, class, etc..

isidentifier() doesn’t check if the string is a Python keyword. It only checks if the string starts with a letter or underscore, followed by letters, numbers, or underscores.

Examples of valid identifiers

  • one

  • _two

  • __three__

  • four_4

Examples of invalid identifiers

  • 4four : Invalid because the identifier should start with a letter or underscore.

  • fa$ : Invalid because the special character is used.

  • continue : Invalid because continue is a Python keyword.

Code example

identifier= "one"
print(identifier, " isidentifier -- ", identifier.isidentifier())
identifier= "4four"
print(identifier, " isidentifier -- ", identifier.isidentifier())
identifier= "continue"
print(identifier, " isidentifier -- ", identifier.isidentifier())

Explanation

  • For the first string, one, the isidentifier() method returns True because it is a valid identifier.

  • For the second string, 4four, the isidentifier() method returns False because it is not a valid identifier.

Identifiers should not start with numbers.

  • For the third string, continue, isidentifier() returns True because even though it is an invalid identifier, the isidentifier method doesn’t check for Python keywords.

How to check for keywords

To check if a string is not a keyword, we can use the iskeyword() method of the keyword module.

from keyword import iskeyword
print(iskeyword('continue')) # True

We can determine if a string is a valid identifier by checking if the string returns True for the isidentifier() method and False for the iskeyword() method.

from keyword import iskeyword
def is_valid_identifier(string):
return string.isidentifier() and (not iskeyword(string))
print(is_valid_identifier('continue'))
print(is_valid_identifier('fa$'))
print(is_valid_identifier('1fa'))
print(is_valid_identifier('one_2_three'))
print(is_valid_identifier('__'))

Free Resources