Sunday, January 23, 2022

ItsMyCode: 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


from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...