Check whether the given string is a valid identifier in Python


Suppose we have a string representing an identifier. We have to check whether it is valid or not. There are few criteria based on which we can determine whether it is valid or not.

  • It must start with underscore '_' or any uppercase or lowercase letters
  • It does not contain any whitespace
  • All the subsequent characters after the first one must not consist of any special characters like $, #, % etc.

If all of these three are valid then only the string is valid identifier.

So, if the input is like id = "_hello_56", then the output will be True.

To solve this, we will follow these steps −

  • if first character in s is not alphabetic and not underscore, then
    • return False
  • for each character ch in s[from index 1 to end], do
    • if ch is not alphanumeric and ch is not underscore, then
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(s):
   if not s[0].isalpha() and s[0] != '_':
      return False

   for ch in s[1:]:
      if not ch.isalnum() and ch != '_':
         return False

   return True

id = "_hello_56"
print(solve(id))

Input

"_hello_56"

Output

True

Updated on: 16-Jan-2021

680 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements