DEV Community

Srinivas Ramakrishna for ItsMyCode

Posted on • Originally published at itsmycode.com on

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.

Also read How to Find Unique Values in a Column in Pandas

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()
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

Output

False
True
False
True
True
False
Enter fullscreen mode Exit fullscreen mode

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))

Enter fullscreen mode Exit fullscreen mode

Output

ItsMyCode is an identifier
$$ItsMyCode$$ is not a valid identifier
Enter fullscreen mode Exit fullscreen mode

Top comments (0)