Python String isidentifier() Function
The String isidentifier()
method returns True
if the string is a valid identifier according to the language definition. Otherwise, it returns False
.
A valid identifier can only have alphanumeric characters a-z
, A-Z
, 0-9
and underscore _
. The first character of an identifier can not be a digit. Also, identifier should not match a Python keyword (because it is a reserved identifier).
Syntax
my_string.isidentifier()
isidentifier() Parameters
Python String isidentifier()
function does not take any parameters.
isidentifier() Return Value
Python String isidentifier()
function returns:
True
if the string is a valid identifier.False
if 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: True
output
True
An 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: False
output
True
False
False
An 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: True
output
False
True
Example 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: True
output
True
To test if a string matches a Python keyword, use keyword.iskeyword()
:
from keyword import iskeyword
print(iskeyword('class')) # Output: True
output
True
A string is considered a valid identifier if .isidentifier()
returns True
and iskeyword()
returns False
.
from keyword import iskeyword
my_str = "myidentifier"
if my_str.isidentifier() and not iskeyword(my_str):
print(f"'{my_str}' is a valid identifier")
else:
print(f"'{my_str}' is not a valid identifier")
output
'myidentifier' is a valid identifier