Python String isidentifier() Method

The isidentifier() method checks whether a string is valid identifier string or not. It returns True if the string is a valid identifier otherwise returns False.

A valid identifier string can only contain uppercase or lowercase alphabats A to Z, underscore, digits 0 to 9, and must start with an alphabats or an underscore. Learn more about identifier in Python.

Syntax :

str.isidentifier()

Parameter :

None

Return Value:

Returns True if a string is an identifier; otherwise returns False.

The following example demonstrates the isidentifier() method.

Example: isidentifier()
>>> lang='Python'
>>> lang.isidentifier()
True
>>> greet='Hello World' 
>>> greet.isidentifier() # includes space so returns False
False

The following example contains numbers and symbols along with alphabets.

Example: isidentifier()
>>> 'JamesBond_007'.isidentifier()
True
>>> '_hello_world'.isidentifier()
True

The is.identifier() method will return True if the string does not contain numbers(0-9) in the starting position. It will return True if there is an underscore regardless of its position.

The following example contains numerical values as first character and whitespaces

Example: isidentifier()
>>> '1 Harbour side'.isidentifier()
False
>>> 'Hello World'.isidentifier()
False
>>> '#1'.isidentifier()
False
>>> ''.isidentifier()
False

The is.identifier() method will return False if the first character of the string is numerical(0-9) or contains whitespaces. An empty string will return False.

The following table lists difference among the isalpha(), isalnum(), and isidentifier() methods based on the given inputs:

Input String isaplha() isalnum() isidentifier()
'123' False True False
'$123' False False False
'XYZ123' False True True
'123XYZ' False True False
'_123XYZ' False False True
'_XYZ_123' False False True
'-XYZ-123' False False False
'.XYZ.123' False False False
Want to check how much you know Python?