Python String isidentifier() Method

The isidentifier() method checks whether a string is a valid Python identifier.

An identifier is a name used to identify variables, functions, classes, modules, or other objects.

Syntax

string.isidentifier()

Parameter

No parameter.

Return Value

Returns True if the string is a valid identifier.

Returns False otherwise.

Rules for a Valid Python Identifier

A valid Python Identifier:

  • Must start with a letter (a-z or A-Z) or an underscore (_).
  • Can contain letters, digits (0-9), and underscores after the first character.
  • Cannot be a Python reserved keyword like if, for, while, etc. The isidentifier() method does not check whether the string is a reserved keyword.
  • Cannot contain spaces or special characters (@, $, !, etc.).

Examples

Check if a String is a Valid Identifier

# Valid Identifiers
print("name".isidentifier())       # True
print("_private".isidentifier())   # True
print("user_email".isidentifier()) # True
print("userEmail".isidentifier())  # True
print("user2".isidentifier())      # True

# Invalid Identifiers
print("2user".isidentifier())      # False (starts with digit)
print("user email".isidentifier()) # False (contains space)
print("user-email".isidentifier()) # False (contains hypen)
print("if".isidentifier())         # True (But it is a keyword. See the rules for a valid identifier)