Skip to content

Python String isidentifier() Method

Check whether a string is a valid Python identifier using the isidentifier() method, including rules for alphanumeric characters, underscores, and keyword exclusions.

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:

  • 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
Navigation