Last Updated : 04 Jan, 2025
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:
Python
s = "variable_name"
print(s.isidentifier())
Explanation:
"variable_name"
follows all the rules of a valid Python identifier:
True
.Parameters
string.isidentifier()
isidentifier()
method does not take any parameters.True
if the string is a valid identifier.False
otherwise.An identifier cannot start with a number.
Python
# Starts with a number
s = "1variable"
print(s.isidentifier())
Explanation:
"1variable"
begins with the digit 1
, which violates the rules for identifiers.False
.Special characters, apart from the underscore, are not allowed in identifiers.
Python
s = "var!name" # Contains a special character (!)
print(s.isidentifier())
Explanation:
"var!name"
includes the special character !
, making it an invalid identifier.False
.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:
Python
s = "class" # Reserved keyword in Python
print(s.isidentifier())
Explanation:
"class"
follows all identifier rules, so isidentifier()
returns True
.SyntaxError
because it is a reserved keyword.An empty string cannot qualify as an identifier:
Python
s = "" # Empty string
print(s.isidentifier())
Explanation:
False
accordingly.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4