Skip to content

Variable Name

Correct variable names consist only of English letters, digits and underscores and they can't start with a digit.

Check if the given string is a correct variable name.

Example

  • For name = "var_1__Int", the output should be

    variable_name(name) = true
  • For name = "qq-q", the output should be

    variable_name(name) = false
  • For name = "2w2", the output should be

    variable_name(name) = false

Solution

py
def variable_name_v1(name):
    if name[0].isdigit() or (not name.replace('_', '').isalnum()):
        return False
    return True


def variable_name_v2(name):
    return name.isidentifier()


print(variable_name_v1('_abc123__'))
js
function variable_name_v1(name) {
  return /^[a-zA-Z_]\w*$/.test(name);
}

console.log(variable_name_v1('_abc123__'));

my thoughts are neither my employer's nor my wife's