Python | Check if string is a valid identifier
Last Updated :
16 Mar, 2023
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)
OutputValid 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
OutputValid 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 :
- Import the keyword module.
- Define a function check() that takes a string as input.
- 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. - 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". - 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)
OutputValid 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.
Similar Reads
How to Check if a Variable is a String - Python The goal is to check if a variable is a string in Python to ensure it can be handled as text. Since Python variables can store different types of data such as numbers, lists or text, itâs important to confirm the type before performing operations meant only for strings. For example, if a variable co
3 min read
Python | Check whether a string is valid json or not Given a Python String, the task is to check whether the String is a valid JSON object or not. Let's try to understand the problem using different examples in Python. Validate JSON String in PythonThere are various methods to Validate JSON schema in Python here we explain some generally used methods
3 min read
Check if String is Empty or Not - Python We are given a string and our task is to check whether it is empty or not. For example, if the input is "", it should return True (indicating it's empty), and if the input is "hello", it should return False. Let's explore different methods of doing it with example:Using Comparison Operator(==)The si
2 min read
Python - Check if String contains any Number We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
2 min read
Python | Check Numeric Suffix in String Sometimes, while programming, we can have such a problem in which we need to check if any string is ending with a number i.e it has a numeric suffix. This problem can occur in Web Development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using regex This problem
6 min read
Python Check If String is Number In Python, there are different situations where we need to determine whether a given string is valid or not. Given a string, the task is to develop a Python program to check whether the string represents a valid number.Example: Using isdigit() MethodPython# Python code to check if string is numeric
6 min read
Check if string contains character - Python We are given a string and our task is to check if it contains a specific character, this can happen when validating input or searching for a pattern. For example, if we check whether 'e' is in the string 'hello', the output will be True.Using in Operatorin operator is the easiest way to check if a c
2 min read
Check for ASCII String - Python To check if a string contains only ASCII characters, we ensure all characters fall within the ASCII range (0 to 127). This involves comparing each character's value to ensure it meets the criteria.Using str.isascii()The simplest way to do this in Python is by using the built-in str.isascii() method,
2 min read
Python program to check if a given string is Keyword or not This article will explore how to check if a given string is a reserved keyword in Python. Using the keyword We can easily determine whether a string conflicts with Python's built-in syntax rules.Using iskeyword()The keyword module in Python provides a function iskeyword() to check if a string is a k
2 min read