In Python 3 you can use str.isidentifier() to test whether a given string is a valid Python identifier/name.

>>> 'X'.isidentifier()
True
>>> 'X123'.isidentifier()
True
>>> '2'.isidentifier()
False
>>> 'while'.isidentifier()
True

The last example shows that you should also check whether the variable name clashes with a Python keyword:

>>> from keyword import iskeyword
>>> iskeyword('X')
False
>>> iskeyword('while')
True

So you could put that together in a function:

from keyword import iskeyword

def is_valid_variable_name(name):
    return name.isidentifier() and not iskeyword(name)

Another option, which works in Python 2 and 3, is to use the ast module:

from ast import parse

def is_valid_variable_name(name):
    try:
        parse('{} = None'.format(name))
        return True
    except SyntaxError, ValueError, TypeError:
        return False

>>> is_valid_variable_name('X')
True
>>> is_valid_variable_name('123')
False
>>> is_valid_variable_name('for')
False
>>> is_valid_variable_name('')
False
>>> is_valid_variable_name(42)
False

This will parse the assignment statement without actually executing it. It will pick up invalid identifiers as well as attempts to assign to a keyword. In the above code None is an arbitrary value to assign to the given name - it could be any valid expression for the RHS.

Answer from mhawke on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_variables_names.asp
Python - Variable Names
A variable name cannot be any of the Python keywords. ... myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" Try it Yourself » ... Variable names with more than one word can be difficult to read. There are several techniques you can use to make them more readable: Each word, except the first, starts with a capital letter: ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
Real Python
realpython.com › python-variables
Variables in Python: Usage and Best Practices – Real Python
January 12, 2025 - They denote that the enclosed part is optional. Yes, you can declare a Python variable without assigning it a value: ... >>> number: int >>> number Traceback (most recent call last): ... NameError: name 'number' is not defined · The variable declaration on the first line works and is valid Python syntax.
🌐
Log2Base2
log2base2.com › programming-language › python3 › basic › need-of-variables-in-python.html
Valid and invalid variable names in Python | Need of variables
1. Variable name should start with letter(a-zA-Z) or underscore (_). ... pass, break, continue.. etc are reserved for special meaning in Python.
Top answer
1 of 6
65

In Python 3 you can use str.isidentifier() to test whether a given string is a valid Python identifier/name.

>>> 'X'.isidentifier()
True
>>> 'X123'.isidentifier()
True
>>> '2'.isidentifier()
False
>>> 'while'.isidentifier()
True

The last example shows that you should also check whether the variable name clashes with a Python keyword:

>>> from keyword import iskeyword
>>> iskeyword('X')
False
>>> iskeyword('while')
True

So you could put that together in a function:

from keyword import iskeyword

def is_valid_variable_name(name):
    return name.isidentifier() and not iskeyword(name)

Another option, which works in Python 2 and 3, is to use the ast module:

from ast import parse

def is_valid_variable_name(name):
    try:
        parse('{} = None'.format(name))
        return True
    except SyntaxError, ValueError, TypeError:
        return False

>>> is_valid_variable_name('X')
True
>>> is_valid_variable_name('123')
False
>>> is_valid_variable_name('for')
False
>>> is_valid_variable_name('')
False
>>> is_valid_variable_name(42)
False

This will parse the assignment statement without actually executing it. It will pick up invalid identifiers as well as attempts to assign to a keyword. In the above code None is an arbitrary value to assign to the given name - it could be any valid expression for the RHS.

2 of 6
3

EDIT: this is wrong and implementation dependent - see comments.

Just have Python do its own check by making a dictionary with the variable holding the name as the key and splatting it as keyword arguments:

def _dummy_function(**kwargs):
    pass

def is_valid_variable_name(name):
    try:
        _dummy_function(**{name: None})
        return True
    except TypeError:
        return False

Notably, TypeError is consistently raised whenever a dict splats into keyword arguments but has a key which isn't a valid function argument, and whenever a dict literal is being constructed with an invalid key, so this will work correctly on anything you pass to it.

🌐
Quora
quora.com › What-are-the-valid-variable-names-in-Python
What are the valid variable names in Python? - Quora
Examples of valid identifiers: x, _x, var1, π, résumé, σ2 · Examples of invalid identifiers: 1var (starts with digit), my-var (hyphen), class (reserved keyword) Reserved keywords (cannot be used as variable names) — Python 3.12+ (common list; check your interpreter for the exact set up to May 2024) False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
🌐
Note.nkmk.me
note.nkmk.me › home › python
Valid Variable Names and Naming Rules in Python | note.nkmk.me
May 5, 2023 - 2. Lexical analysis - Keywords — Python 3.11.3 documentation · Note that isidentifier() returns True for reserved words and keywords since they are valid strings. However, using them as identifiers (variable names, function names, class names, etc.) will raise an error.
🌐
W3Resource
w3resource.com › python-interview › what-are-variables-in-python-rules-for-naming-variables-in-python.php
Python variables: Definition, assignment, and naming rules
August 12, 2023 - The convention is to use lowercase letters for variable names, with underscores (_) to separate words in multi-word variable names (snake_case). For example, my_variable, student_age, total_amount, item_price.
🌐
W3Schools
w3schools.com › python › python_variables.asp
Python Variables
Variable names are case-sensitive. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send ...
Find elsewhere
🌐
Learn with Yasir
yasirbhutta.github.io › python › docs › variables › variables-basics.html
Python Variables Explained: Basics, Naming Rules & Practical Examples | Learn with Yasir
Python has 35 reserved keywords (e.g., if, for, while). ... | Valid ✅ | Invalid ❌ | |——————-|——————–| | user_name | user-name (hyphen)| | _total | 2nd_place (starts with digit)| | price2 | class (reserved keyword)|
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-variables
Python Variables - GeeksforGeeks
Unlike Java and many other languages, Python variables do not require explicit declaration of type. The type of the variable is inferred based on the value assigned. ... Variable names can only contain letters, digits and underscores (_).
Published   3 weeks ago
🌐
Codefinity
codefinity.com › courses › v2 › 2f60173b-9829-4c84-8548-85bf65183f71 › 984eb7ed-25b1-40e1-93d0-3f7991547ac9 › 9078d240-0669-41e4-a40c-9e4538c36fad
Learn Variable Naming Rules | Variables and Types
For example `item_name` is a valid variable print = 5.0 # You cannot use reserved keywords as a variable # But you can use these words in combination with others to name a variable # For example, `print_quantity = 5.0` is valid. ... You can attempt to correct the variable names above to ensure the code runs without errors. Properly named variables enhance code readability and maintainability. Following Python's naming conventions is crucial to avoid syntax errors and other potential issues.
🌐
W3docs
w3docs.com › quiz › question › ZGN5BN==
Which of the following is not a valid variable name in Python?
The reasons why the name "2variable" ... reason why "2variable" isn't a valid variable name. Variable names in Python should start with either a letter or an underscore (_)....
🌐
Brainly
brainly.com › computers and technology › high school › which of the following is a valid variable name in python? a. new variable b. 2021summer c. new-variable d. newvariable
[FREE] Which of the following is a valid variable name in Python? A. new Variable B. 2021Summer C. new-variable - brainly.com
An example of a valid variable name could be 'age' or 'total_sum', while examples of invalid names include '1stPlace' (starts with a number) or 'my name' (contains a space). According to Python's official documentation, variable names must follow ...
🌐
Python
peps.python.org › pep-0008
PEP 8 – Style Guide for Python Code | peps.python.org
Names of type variables introduced in PEP 484 should normally use CapWords preferring short names: T, AnyStr, Num.
🌐
Brainly
brainly.com › computers and technology › high school › which of the following is not a valid variable in python? a. _var b. var_name c. var11 d. 5var
[FREE] Which of the following is not a valid variable in Python? a. _var b. var_name c. var11 d. 5var - brainly.com
These rules include: Variable names must start with a letter (a-z, A-Z) or an underscore (_). After the first character, variable names can include letters, digits (0-9), and underscores.
🌐
Runestone Academy
runestone.academy › ns › books › published › py4e-int › variables › variable-names-keywords.html
2.3. Variable names and keywords — Python for Everybody - Interactive
The variable name 76trombones is illegal because it begins with a number. The name more@ is illegal because it contains an illegal character, @. But what’s wrong with class? It turns out that class is one of Python’s keywords.
🌐
Apmonitor
apmonitor.com › che263 › index.php › Main › PythonBasics
Python Programming Basics
Valid variable names include: myVar myVariable my4Variable myVariable4 _myVariable __myVariable MYVARIABLE myvariable · Invalid variable names include those that start with a number, have a space in the name, or contain special characters such as: ... There are reserved keywords in Python ...
🌐
Python Land
python.land › home › variable naming
Variable naming • Python Land
April 2, 2024 - If we were calculating the total price of a shopping cart here, for example, a good name would be shopping_cart_total. Don’t skimp on the number of characters in your variable names. It’s better to have clean, readable names like shopping_cart_total instead of an abbreviation like sct.