Python String isidentifier() Method
The Python String isidentifier() method is used to check whether a string is a valid identifier. An identifier is a name used to identify variables, functions, classes, modules, or other objects in Python code.
A string is considered a valid identifier if −
- It starts with a letter (a-z, A-Z) or an underscore "_".
- The remaining characters in the string are letters, digits (0-9), or underscores _.
Syntax
Following is the basic syntax of the Python String isidentifier() method −
string.isidentifier()
Parameters
This method does not accept any parameter.
Return Value
The method returns a boolean value "True" or "False". It returns "True" if the string is a valid identifier according to Python syntax rules, otherwise it returns "False".
Example 1
In the following example, we are checking whether the string "my_variable" is a valid Python identifier using the isidentifier() method −
identifier = "my_variable"
result = identifier.isidentifier()
print("The result is:",result)
Output
The output obtained is as follows −
The result is: True
Example 2
Here, we use the isidentifier() method to check whether the string "class" is a valid Python identifier −
identifier = "class"
result = identifier.isidentifier()
print("The result is:",result)
Output
Despite being a reserved keyword, "class" is still a valid identifier, so the isidentifier() method returns True as shown in the output below −
The result is: True
Example 3
In the following example, we check whether the "underscores" are valid identifiers using the isidentifier() method −
identifier = "_"
result = identifier.isidentifier()
print("The result is:",result)
Output
The result produced is as shown below −
The result is: True
Example 4
In here, we check whether the string "123variable" is a valid Python identifier, which it isn't because identifiers cannot start with a digit. Therefore, the isidentifier() method returns False −
identifier = "123variable"
result = identifier.isidentifier()
print("The result is:",result)
Output
We get the output as shown below −
The result is: False