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.

In this article, we will learn about the Python String isidentifier() method with the help of examples.

isidentifier() Syntax

The Syntax of isidentifier() method is:

string.isidentifier()

isidentifier() Parameters

The isidentifier() method does not take any parameters.

isidentifier() Return Value

The isidentifier() method returns

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

Checkout to documentation to learn more about What is a valid identifier in Python?

Example 1: How isidentifier() works?


# 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 1: How to use isidentifier() method?

# 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.

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
Python String Lstrip()

Python String lstrip()

Table of Contents Hide lstrip() Syntaxlstrip() Parameterslstrip() Return ValueExample 1: Working of lstrip()Example 2 – How to use lstrip() method in real world? The Python String lstrip() method is a…
View Post
Calculate Euclidean Distance In Python

Calculate Euclidean Distance in Python

Table of Contents Hide How to Calculate Euclidean Distance in Python?Method 1: Using linalg.norm() Method in NumPyMethod 2: Using dot() and sqrt() methodsMethod 3: Using square() and sum() methodsMethod 4:…
View Post
Python String Lower()

Python String lower()

Table of Contents Hide lower() Syntax lower() Parameterslower() Return ValueExample 1: Convert a string to lowercaseExample 2: String with Alphanumeric charactersExample 3: How to check if two strings are same…
View Post