The String isidentifier() method returns True if the string is a valid identifier according to the language definition. Otherwise, it returns False.
Syntax
my_string.isidentifier()isidentifier() Parameters
Python String isidentifier() method does not take any parameters.
isidentifier() Return Value
Python String isidentifier() method returns:
Trueif the string is a valid identifier.Falseif the string is not a valid identifier.
Examples
Example 1: Check if a String is an identifier with isidentifier()
The isidentifier() method returns True if the string is a valid identifier.
my_str = 'myIdentifier'
result = my_str.isidentifier()
print(result) # Output: Trueoutput
TrueAn identifier can contain an underscore but not a special character.
my_str1 = 'my_identifier'
my_str2 = 'my identifier'
my_str3 = 'my-identifier'
print(my_str1.isidentifier()) # Output: True
print(my_str2.isidentifier()) # Output: False
print(my_str3.isidentifier()) # Output: Falseoutput
True
False
FalseAn identifier can contain a digit, except for the first character.
my_str1 = '123myIdentifier'
my_str2 = 'myIdentifier123'
print(my_str1.isidentifier()) # Output: False
print(my_str2.isidentifier()) # Output: Trueoutput
False
TrueExample 2: Check if a Python Keyword is an identifier with isidentifier()
The isidentifier() method returns True for a string that matches a Python keyword, even though it is not a valid identifier.
print('class'.isidentifier()) # Output: Trueoutput
TrueTo test if a string matches a Python keyword, use keyword.iskeyword():
from keyword import iskeyword
print(iskeyword('class')) # Output: Trueoutput
True