Python String isidentifier()

The Python String isidentifier() method is a built-in function that returns true if the string is a valid identifier. If not it returns False.

Syntax

The Syntax of isidentifier() method is:

string.isidentifier()

Parameters

The isidentifier() method does not take any parameters.

Return Value

The isidentifier() method returns

  • True if the string is a valid identifier
  • False if the string is not a valid identifier

Check out the documentation to learn more about What is a valid identifier in Python?

Example 1: How isidentifier() method work


# Python code to illustrate 
# the working of isidentifier()
  
# String with spaces
string = "Its My Code"
print(string.isidentifier())
  
# A Valid identifier
string = "ItsMyCode"
print(string.isidentifier())
  
# Empty string
string = ""
print(string.isidentifier())

# Underscore string
string = "_"
print(string.isidentifier())
  

# Alphanumeric string
string = "ItsMyC0de123"
print(string.isidentifier())
  
# Beginning with an integer
string = "123ItsMyCode"
print(string.isidentifier())

Output

False
True
False
True
True
False

Example 2: How to use isidentifier() method in actual program

# Python isidentifier() method example

str = "ItsMyCode"
# check if the string is valid identifier
if str.isidentifier() == True:
    print("{text} is an identifier".format(text=str))
else:
    print("{text} is not a valid identifier".format(text=str))
str2 = "$$ItsMyCode$$"
if str2.isidentifier() == True:
    print("{text} is an identifier".format(text=str2))
else:
   print("{text} is not a valid identifier".format(text=str2))

Output

ItsMyCode is an identifier
$$ItsMyCode$$ is not a valid identifier
Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Numpy.repeat() Function

numpy.repeat() Function

Table of Contents Hide SyntaxRepeat ParametersReturn ValueExample 1: Repeating the Single-Dimensional NumPy ArrayExample 2: Repeating the Two-Dimensional NumPy ArrayExample 3: Repeating the NumPy Array Row WiseExample 4: Repeating the NumPy…
View Post