Python Reference ยท String Methods
Python str.isidentifier() method
Reference for Python str.isidentifier(): check whether a string is a syntactically valid name, why keywords still pass, and how to combine it with keyword.iskeyword().
The isidentifier() method returns True if the string is a valid Python identifier according to the language definition: it starts with a letter or underscore, and the rest are letters, digits or underscores. Unicode letters are allowed, so "cafรฉ" and "ๅๅ" are valid names.
It checks syntax only. Reserved words such as class look like identifiers, so they pass too. Combine it with the keyword module when you need a name you can really assign to.
print("total_2".isidentifier()) # True print("2total".isidentifier()) # False
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.isidentifier()
This method takes no parameters.
Return value: True if the string is a valid identifier, False otherwise (including for the empty string).
Raises: nothing.
Usage notes
- Keywords pass.
"class".isidentifier(),"None".isidentifier()and"for".isidentifier()are allTrue. Usekeyword.iskeyword(text)to reject them. - Soft keywords such as
matchandcaseare legal variable names and are not reported bykeyword.iskeyword(); they appear inkeyword.softkwlist. - Case matters.
"None"is a keyword,"none"is an ordinary name. - Unicode is normalized by Python, not by this method. Identifiers are NFKC-normalized when source code is parsed, so two spellings can refer to the same name in code, yet
isidentifier()only tests the string you give it. - Useful for dynamic code. Check names before using them with
setattr(),namedtuple,dataclasses.make_dataclassor when generating code. Note thatsetattr()itself accepts any string, so the check is yours to make. - Leading underscores are valid, including dunder names such as
"__init__". - Whitespace is not trimmed.
" name".isidentifier()isFalse; callstrip()first if the input may have spaces.
Related
str.isalnum(),str.isalpha(),str.isascii(),setattr()- Lessons: String methods, Variables