Python String isidentifier()
Method
The isidentifier() method in Python is used to check whether a given string is a valid Python identifier. An identifier is a name used to identify variables, functions, classes, modules, etc.
Syntax
string.isidentifier()
Parameters:
- No parameters required.
Returns:
True
if the string is a valid identifier.False
otherwise.
What is a Valid Identifier?
- Only contains letters (A–Z, a–z), digits (0–9), and underscores (_)
- Cannot start with a digit
- Cannot contain spaces or special characters
- Cannot be a Python keyword (though
isidentifier()
won't check for keywords)
Example 1: Valid Identifier
name = "my_variable"
print(name.isidentifier())
True
Example 2: Starts with a Digit
name = "1variable"
print(name.isidentifier())
False
Example 3: Contains a Space
name = "my var"
print(name.isidentifier())
False
Example 4: Underscore is Allowed
name = "_temp123"
print(name.isidentifier())
True
Use Cases
- Validating variable names in dynamic code generation
- Building programming tools or editors
- Checking user input before creating variable-like data
Common Mistakes
- Thinking it checks for Python
keywords
– it doesn't."class"
is a valid identifier technically, but cannot be used as a variable. - Confusing it with
isalnum()
– which only checks for letters and digits, not identifier rules.
Interview Tip
Be ready to explain the difference between isidentifier()
and isalnum()
, and what makes a valid identifier in Python.
Summary
isidentifier()
checks if a string is a valid Python identifier- Returns
True
if valid,False
if not - Useful for code generation, validation, and linters
Practice Problem
Write a program that takes input from the user and tells whether it's a valid identifier.
user_input = input("Enter a variable name: ")
if user_input.isidentifier():
print("Valid identifier")
else:
print("Invalid identifier")