Python String isidentifier() Method

Python String Isidentifier() Method

This is a tutorial of the Python String isidentifier() method. Learn to check if a given string is a valid Python Identifier or not with the help of examples.

Python String isidentifier()

The str.isidentifier() method returns True if the given string is a valid Python Identifier and False if its not.

Note. An Identifier is the name of the Python Objects, like classes, functions, variables, modules, etc.

Syntax

Given below is the syntax of the str.isidentifier() method.

isidentifier() Parameters

This method does not take any arguments as it only checks the given string on which it is applied, so no additional data is required in the form of arguments.

isidentifier() Return Value

It returns the boolean value True or False according to the following logic.

  • Returns True if the given string is a valid identifier in Python.
  • Returns False if the given string is not a valid identifier in Python.

Examples

Given below are the two examples demonstrating the usage of the Python String isidentifier() method.

Example 1. Checking a given String is a valid identifier or not using str.isidentifier() method

In this example, we’re applying the method isidentifier() on several different strings to check the result, for what strings it returns True and for what it returns False.

#Alphabetical String
word = 'hello'
print(word.isidentifier())

#Alphanumeric String
word = 'hello12345'
print(word.isidentifier())

#Variable Names in Python can not start with a number, so it is not a valid identifier
word = '1hello'
print(word.isidentifier())

#Name starting with _
word = '_hello'
print(word.isidentifier())

#Empty String
word = ''
print(word.isidentifier())

Output.

True
True
False
True
False

Example 2. Using the Python String isidentifier() method with if-else statement

In the following example, we’ve directly used the str.isidentifier() method as the condition for the if-else statement to print a string accordingly after checking if the given string is a valid identifier or not.

#Using str.isidentifier() with if-else statement

#Given String
name = "HelloWorld12345"

if name.isidentifier():
    print("String contained in the variable name is a valid identifier.")
else:
    print("String contained in the variable name is not a valid identifier.")

Output.

String contained in the variable name is a valid identifier.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

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