Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Check if string is a valid identifier

Python | Check if string is a valid identifier

Given a string, write a Python program to check if it is a valid identifier or not. 
An identifier must begin with either an alphabet or underscore, it can not begin with a digit or any other special character, moreover, digits can come after

gfg : valid identifier
123 : invalid identifier
_abc12 : valid identifier
#abc : invalid identifier

In this program, we are using search() method of regex module. 
re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. 
Let’s see the Python program to determine whether string is an identifier or not.
 

Python3




# Python program to identify the identifier
 
# import re module
 
# re module provides support
# for regular expressions
import re
 
# Make a regular expression
# for identify valid identifier
regex = '^[A-Za-z_][A-Za-z0-9_]*'
     
# Define a function for
# identifying valid identifier
def check(string):
 
     # pass the regular expression
     # and the string in search() method
    if(re.search(regex, string)):
        print("Valid Identifier")
         
    else:
        print("Invalid Identifier")
     
 
# Driver Code
if __name__ == '__main__' :
     
    # Enter the string
    string = "gfg"
     
    # calling run function
    check(string)
 
    string = "123"
    check(string)
 
    string = "#abc"
    check(string)


Output

Valid Identifier
Invalid Identifier
Invalid Identifier

Using the isidentifier method:
This method checks if the string is a valid identifier according to the Python language specification. It returns True if the string is a valid identifier, and False otherwise.

Python3




# Python program to identify the identifier
# Define a function for
# identifying valid identifier
def check(string):
    if string.isidentifier():
        print("Valid Identifier")
    else:
        print("Invalid Identifier")
 
# Driver code
# Enter the string
string = "gfg"
# calling run function
check(string)
 
string = "123"
check(string)
 
string = "_abc12"
check(string)
#This code is contributed by Edula Vinay Kumar Reddy


Output

Valid Identifier
Invalid Identifier
Valid Identifier

Time complexity: O(n), where n is the length of the string.
Auxiliary Space:  O(1), since this method does not create any additional data structures.

Method #3: Using the keyword module

Step-by-Step Algorithm : 

  1. Import the keyword module.
  2. Define a function check() that takes a string as input.
  3. Check whether the input string is a Python keyword using the iskeyword() function from the keyword module:
     3a. If the string is a keyword, print “Invalid Identifier: it is a Python keyword”.
     3b. If the string is not a keyword, continue to the next step.
  4. Check whether the input string is a valid Python identifier using the isidentifier() method:
    4a. If the string is a valid identifier, print “Valid Identifier”.
    4b. If the string is not a valid identifier, print “Invalid Identifier”.
  5. End of the function.

Python3




import keyword
 
def check(string):
    if keyword.iskeyword(string):
        print("Invalid Identifier: it is a Python keyword")
    elif not string.isidentifier():
        print("Invalid Identifier")
    else:
        print("Valid Identifier")
 
 
 
# Driver Code
if __name__ == '__main__' :
     
    # Enter the string
    string = "gfg"
     
    # calling run function
    check(string)
 
    string = "123"
    check(string)
 
    string = "#abc"
    check(string)


Output

Valid Identifier
Invalid Identifier
Invalid Identifier

Complexity Analysis : 

Time Complexity: O(1), This is because both the iskeyword() function and the isidentifier() method have constant time complexity and also the conditional checks are taking constant time. So overall time complexity is O(1).
Auxiliary Spacey: O(1), This is because it uses a constant amount of additional memory that does not depend on the input size.

RELATED ARTICLES

Most Popular

Recent Comments