The Python isidentifier()
method checks if a string is a valid identifier or not.
string.isidentifier()
The isidentifier()
method returns True
if the string is a valid identifier; otherwise, it returns False
.
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
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.
one
_two
__three__
four_4
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.
identifier= "one"print(identifier, " isidentifier -- ", identifier.isidentifier())identifier= "4four"print(identifier, " isidentifier -- ", identifier.isidentifier())identifier= "continue"print(identifier, " isidentifier -- ", identifier.isidentifier())
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.
continue
, isidentifier()
returns True
because even though it is an invalid identifier, the isidentifier
method doesn’t check for Python 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 iskeyworddef 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('__'))