Skip to content
Tutorials Center
My learning

Topics

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.

Python
print("total_2".isidentifier())   # True
print("2total".isidentifier())    # False

Try it

Python Valid and invalid names

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.

Python Checking that a name is safe to use

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

Python
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 all True. Use keyword.iskeyword(text) to reject them.
  • Soft keywords such as match and case are legal variable names and are not reported by keyword.iskeyword(); they appear in keyword.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_dataclass or when generating code. Note that setattr() 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() is False; call strip() first if the input may have spaces.