Python String isidentifier()

Python String isidentifier() method returns True if given string is a valid identifier, else it returns False.

Identifiers are names given to variables, class, functions, etc., to identify or reference them in a program.

In this tutorial, we will learn the syntax and examples for isidentifier() method of String class.

Rules for Naming Identifiers

  1. An identifier can contain only alphabets, decimals or underscore.
  2. An identifier cannot start with a digit.

Syntax

The syntax of String isidentifier() method in Python is

</>
Copy
str.isidentifier()

Example

In this example, we will take a string 'string_1', and check if this string is a valid identifier or not using str.isidentifier() method.

Python Program

</>
Copy
x = 'string_1'
result = x.isidentifier()
print(result)

Output

True

Since, the string obeys all the rules for naming an identifier, the string is a valid identifier and isidentifier() method returns True.

String starts with Digit

In this example, we will take a string '4abs', and check if this string is a valid identifier using str.isidentifier() method. Since the string starts with a decimal character 4, isidentifier() returns False.

Python Program

</>
Copy
x = '4abs'
result = x.isidentifier()
print(result)

Output

False

String starts with Underscore

In this example, we will take a string '_a', and check if this string is a valid identifier using str.isidentifier() method. Since the string starts with an underscore, which is valid for an identifier, isidentifier() returns True.

Python Program

</>
Copy
x = '_a'
result = x.isidentifier()
print(result)

Output

True

Conclusion

In this Python Tutorial, we learned how to check if given string is a valid identifier or not, using String method – isidentifier().