Validate a Python Identifier

Medium ⏱ 12 min 55% acceptance ★★★★★ 4.8
Write is_valid_identifier(s) that returns True if s would be a legal Python variable name: non-empty, starts with a letter or underscore, and every subsequent character is a letter, digit, or underscore. Implement the checks manually (character by character), without calling str.isidentifier().

Examples

Example 1
Input
s = '_my_var1'
Output
True
Explanation

Starts with underscore; rest are letters/digits/underscore.

Example 2
Input
s = '2fast'
Output
False
Explanation

Cannot start with a digit.

Example 3
Input
s = 'my-var'
Output
False
Explanation

Hyphen is not allowed inside an identifier.

Constraints

  • 0 <= len(s) <= 200

Topics

StringsValidation

Companies

InfosysHCLTech

Hints

Hint 1

Check s[0] with `.isalpha()` or equal to '_'.

Hint 2

Check every remaining character with `.isalnum()` or equal to '_'.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.