Python String isidentifier() Method
The isidentifier() method in Python is used to check whether a given string 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 the isidentifier() method works:
Let's understand with the help of an example:
s = "variable_name"
print(s.isidentifier())
Output
True
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.
Table of Content
Syntax of isidentifier()
string.isidentifier()
Parameters
- The
isidentifier()method does not take any parameters.
Return Type
- Returns
Trueif the string is a valid identifier. - Returns
Falseotherwise.
Examples of isidentifier method()
1. Starting with a number
An identifier cannot start with a number.
# Starts with a number
s = "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.
s = "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’s reserved keywords cannot be used as identifiers. While they follow the naming rules, their special meaning in the language makes them invalid as identifiers:
s = "class" # Reserved keyword in Python
print(s.isidentifier())
Explanation:
- The string
"class"follows all identifier rules, soisidentifier()returnsTrue. - However, using it as an identifier in code will lead to a
SyntaxErrorbecause it is a reserved keyword.
4. Empty string
An empty string cannot qualify as an identifier:
s = "" # Empty string
print(s.isidentifier())
Explanation:
- The string is empty, so it cannot meet the rules for identifiers.
- The method returns
Falseaccordingly.