Theisidentifier()
method inPython is used to check whether a givenstring qualifies as a valid identifier according to the Python language rules. Identifiers are names used to identify variables, functions, classes, and other objects. A valid identifier must begin with a letter (A-Z or a-z) or an underscore (_), should contain only alphanumeric characters (A-Z, a-z, 0-9) and underscores (_), and should not be a reserved keyword in Python. In this article, we will see how theisidentifier()
method works:
Let's understand with the help of an example:
Pythons="variable_name"print(s.isidentifier())
Explanation:
- The string
"variable_name"
follows all the rules of a valid Python identifier:- It contains only letters, digits, and underscores.
- It does not start with a digit.
- It is not a Python keyword.
- Hence, the method returns
True
.
Syntax of isidentifier()
string.isidentifier()
Parameters
- The
isidentifier()
method does not take any parameters.
Return Type
- Returns
True
if the string is a valid identifier. - Returns
False
otherwise.
Examples of isidentifier method()
1. Starting with a number
Anidentifier cannot start with a number.
Python# Starts with a numbers="1variable"print(s.isidentifier())
Explanation:
- The string
"1variable"
begins with the digit1
, which violates the rules for identifiers. - Consequently, the method returns
False
.
2. Containing special characters
Special characters, apart from the underscore, are not allowed in identifiers.
Pythons="var!name"# Contains a special character (!)print(s.isidentifier())
Explanation:
- The string
"var!name"
includes the special character!
, making it an invalid identifier. - The method appropriately returns
False
.
3. Reserved keywords
Python’sreserved keywordscannot be used as identifiers. While they follow the naming rules, their special meaning in the language makes them invalid as identifiers:
Pythons="class"# Reserved keyword in Pythonprint(s.isidentifier())
Explanation:
- The string
"class"
follows all identifier rules, soisidentifier()
returnsTrue
. - However, using it as an identifier in code will lead to a
SyntaxError
because it is a reserved keyword.
4. Empty string
An empty string cannot qualify as an identifier:
Pythons=""# Empty stringprint(s.isidentifier())
Explanation:
- The string is empty, so it cannot meet the rules for identifiers.
- The method returns
False
accordingly.