Python string isidentifier method explanation with example

Python string isidentifier() method:

The isidentifier() method is used to check if a string is a valid identifier or not in Python. It returns one boolean value. Identifiers in python are also referred to as names.

A string is called a valid identifier if it includes only characters which could be:

  • Uppercase or lowercase A to Z characters
  • Underscore _
  • Digits from 0 to 9, but it should not be the first character of the string.

Also, it shouldn’t include any spaces.

Let’s learn how isidentifier() method works and how we can use it to check if a string is identifier or not.

isidentifier() method definition:

The isidentifier() method is defined as like below:

str.isidentifier()

Where, str is the given string.

Return value of isidentifier():

The isidentifier() method returns one boolean value. It returns True if the string str is an identifier, else it returns False.

Parameter of isidentifier():

The isidentifier() method doesn’t take any parameter. If you pass any parameter, it will throw an exception.

Example of isidentifier():

Let’s take an example to learn how isidentifier() method works:

str_list = ['hello', 'hello_world', 'hello_123_world',
            '_hello', '123hello', '123Hello', 'Hello World']

for s in str_list:
    print(f'{s} => {s.isidentifier()}')

In this program, str_list is a list of strings. It is using a for loop to iterate over the strings of this list and calls isidentifier() on each.

It will print the below output:

hello => True
hello_world => True
hello_123_world => True
_hello => True
123hello => False
123Hello => False
Hello World => False

Here,

  • 123hello is not an identifier because it starts with a number.
  • 123Hello is not an identifier because it also starts with a number.
  • Hello World is not an identifier as it has one blank space between the words.

It returns True for all other strings.

Check if an user input value is identifier:

Let’s write one program that takes one string as an input from the user and checks if it is an identifier or not:

input_str = input('Enter a string: ')

if input_str.isidentifier():
    print(f'{input_str} is an indentifier')
else:
    print(f'{input_str} is not an indentifier')

It will print output as like below:

Enter a string: 123hello
123hello is not an indentifier

Enter a string: hello_world
hello_world is an indentifier

You might also like: