learn python string isidentifier() with example

The isidentifier() method in Python is a built-in function for string handling. It checks whether the string is a valid identifier or not. An identifier in Python is a name used to identify a variable, function, class, module, or other object. There are certain rules in Python for writing an identifier.

1. Identifiers can be a combination of lowercase (a to z) or uppercase (A to Z) letters, digits (0 to 9), or an underscore (_).

2. An identifier cannot start with a digit.

3. Keywords cannot be used as identifiers.

Syntax:

string.isidentifier()

How to use the isidentifier() method:

str1 = "test_variable"
str2 = "2nd_variable"
str3 = "varWithNumber1"
str4 = "while"

print(str1.isidentifier()) # Output: True
print(str2.isidentifier()) # Output: False
print(str3.isidentifier()) # Output: True
print(str4.isidentifier()) # Output: True but it is a keyword, so should be avoided

Example 1

Checking Valid Identifiers.

valid_identifier = "myVariable"
invalid_identifier = "9myVariable"

print(valid_identifier.isidentifier()) # Output: True
print(invalid_identifier.isidentifier()) # Output: False

Example 2

Checking Empty Strings and Special Characters.

empty_string = ""
special_char = "@var"

print(empty_string.isidentifier()) # Output: False
print(special_char.isidentifier()) # Output: False

Leave a Reply

Your email address will not be published. Required fields are marked *