str.isidentifier()
Added in v3.8 · Updated March 13, 2026 · String Methods
python string methods
The .isidentifier() method checks whether a string is a valid Python identifier. It returns True if the string qualifies as a valid identifier according to Python’s naming rules, and False otherwise.
A valid Python identifier must:
- Start with a letter (a-z, A-Z) or underscore (_)
- Contain only letters, digits (0-9), and underscores
- Not be a Python keyword
Syntax
str.isidentifier()
Parameters
None. This method takes no parameters.
Returns
bool:Trueif the string is a valid identifier,Falseotherwise.
Examples
Basic usage
>>> "hello".isidentifier()
True
>>> "hello_world".isidentifier()
True
>>> "_private".isidentifier()
True
>>> "class".isidentifier()
True # valid identifier, even though it's a keyword
Invalid identifiers
>>> "123abc".isidentifier()
False # starts with a digit
>>> "hello world".isidentifier()
False # contains a space
>>> "hello-world".isidentifier()
False # contains a hyphen
>>> "".isidentifier()
False # empty string
Using with other string methods
# Filter valid identifiers from a list
names = ["valid_name", "123invalid", "another-valid", "okay"]
valid = [name for name in names if name.isidentifier()]
print(valid) # ['valid_name', 'okay']
# Chain with other validation
def is_valid_variable(name):
return name.isidentifier() and not name.startswith("_")
>>> is_valid_variable("my_var")
True
>>> is_valid_variable("_private")
False
Practical use cases
This method is useful for:
- Validating user-provided variable names
- Parsing code or config files
- Checking if a string can be used as a Python identifier
- Input validation in code generation tools
- Building linters or code analysis tools
Comparison with related methods
It is easy to confuse .isidentifier() with similar string methods. Here’s how they differ:
.isalpha()returnsTrueif all characters are alphabetic, but allows single characters like “a” which aren’t valid identifiers by themselves..isalnum()returnsTrueif all characters are alphanumeric, which includes digits anywhere in the string..isdigit()returnsTrueonly if all characters are digits.
>>> "hello".isalpha()
True
>>> "hello".isidentifier()
True
>>> "hello123".isalnum()
True
>>> "hello123".isidentifier()
False # contains digits
Note that .isidentifier() returns True for Python keywords like if, class, and return. If you need to exclude keywords, use the keyword module:
Python 3 also supports Unicode identifiers beyond ASCII. This means you can use non-English letters in your variable names:
>>> "café".isidentifier()
True
>>> "变量".isidentifier()
True
>>> "müller".isidentifier()
True
This is useful when writing code for international teams or localized applications.
import keyword
def is_valid_not_keyword(s):
return s.isidentifier() and not keyword.iskeyword(s)
>>> is_valid_not_keyword("class")
False
>>> is_valid_not_keyword("myclass")
True