Python String isidentifier() method “returns True if the string is a valid identifier, otherwise False”.
Here are the key rules for a string to be considered a valid Python identifier :
- String only contains alphanumeric (a to z, A to Z), (0-9), or an underscore (_).
- A string cannot start with a number, contain any spaces, and must begin with a letter or an underscore (_).
- A string cannot be a Python keyword or reserved word.
Syntax
string.isidentifer()
Parameters
It doesn’t contain any parameters.
Return Value
Returns true if the given string is a valid identifier and false in all other cases.
Visual Representation
Example 1: How to Use String isidentifier() Method
string = "Ronaldo"
string2 = "Messi 10"
string3 = "11Neymar"
print(string.isidentifier())
print(string2.isidentifier())
print(string3.isidentifier())
Output
True
False
False
Example 2: Using with conditions
string = "Ronaldo7"
string1 = ""
if(string.isidentifier()):
print("String is a valid identifier")
else:
print("String is not a valid identifier")
if(string1.isidentifier()):
print("String1 is a valid identifier")
else:
print("String1 is not a valid identifier")
Output
String is a valid identifier
String1 is not a valid identifier
Example 3: Checking for keywords
To check if a string is not a keyword, you can use the “iskeyword()” method of the “keyword” module.
from keyword import iskeyword
def is_valid_identifier(string):
return string.isidentifier() and (not iskeyword(string))
print(is_valid_identifier('break'))
print(is_valid_identifier('ronaldo'))
print(is_valid_identifier('__'))
Output
False
True
True