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
🌐
Real Python
realpython.com › python-variables
Variables in Python: Usage and Best Practices – Real Python
January 12, 2025 - These variables follow the rules for creating valid variable names in Python. They also follow best naming practices, which you’ll learn about in the next section. The variable name below doesn’t follow the rules: ... >>> 1099_filed = False File "<input>", line 1 1099_filed = False ^ SyntaxError: invalid decimal literal · The variable name in this example starts with a number, which isn’t allowed in Python.
🌐
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.
🌐
W3Schools
w3schools.com › python › python_variables_names.asp
Python - Variable Names
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
🌐
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 ...
🌐
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 ...
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.

🌐
Tutorial Teacher
tutorialsteacher.com › python › python-variables
Python Variables: A Beginner's Guide to Declaring, Assigning, and Naming Variables in Python
Just assign a value to a variable using the = operator e.g. variable_name = value. That's it. The following creates a variable with the integer value. ... In the above example, we declared a variable named num and assigned an integer value 10 to it.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-variables
Python Variables - GeeksforGeeks
Avoid using Python keywords like if, else, for as variable names. ... 1name = "Error" # Starts with a digit class = 10 # 'class' is a reserved keyword user-name = "Doe" # Contains a hyphen · Basic Assignment: Variables in Python are assigned values using the = operator.
Published   3 weeks ago
🌐
Brainly
brainly.com › computers and technology › high school › which of the following are valid variable names in python? give all that are valid. a. home_address b. age c. return d. var1.3 e. 4 square f. route 66
[FREE] Which of the following are valid variable names in Python? Give all that are valid. A. home_address B. - brainly.com
October 5, 2023 - The valid variable names in Python from the list provided are 'home_address' and 'Age', as they follow the naming rules. The names 'return', 'var1.3', '4 square', and 'route 66' are not valid due to various restrictions.
🌐
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.
🌐
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
Therefore, the only choice that meets these criteria is D: newVariable. 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).
🌐
MAKE ME ANALYST
makemeanalyst.com › home › python programming › python variable names and keywords
Python Variable Names and Keywords - MAKE ME ANALYST
December 10, 2017 - You may use uppercase letters for ... name is long, then you can use underscore character (_) in the name. For example, top_five_members, var_1 etc....
🌐
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
Examples of valid variable names include '_var', 'var_name', and 'var11', while '5var' is an invalid name because it starts with a number. Python's official documentation outlines the rules for valid variable naming, which clearly states that ...
🌐
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.
🌐
BeginnersBook
beginnersbook.com › 2019 › 03 › python-variables
Python Variables with examples
Variable name is known as identifier. There are few rules that you have to follow while naming the variables in Python. 1. The name of the variable must always start with either a letter or an underscore (_). For example: _str, str, num, _num are all valid name for the variables.
🌐
Learn with Yasir
yasirbhutta.github.io › python › docs › variables › variables-basics.html
Python Variables Explained: Basics, Naming Rules & Practical Examples | Learn with Yasir
2name = "Bob" # Error: Starts with digit first-name = "John" # Error: Hyphen not allowed user age = 30 # Error: Contains space · 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)|
🌐
Runestone Academy
runestone.academy › ns › books › published › py4e-int › variables › variable-names-keywords.html
2.3. Variable names and keywords — Python for Everybody - Interactive
It is often used in names with multiple words, such as my_name or airspeed_of_unladen_swallow. Variable names can start with an underscore character, but we generally avoid doing this unless we are writing library code for others to use.
🌐
Python
peps.python.org › pep-0008
PEP 8 – Style Guide for Python Code | peps.python.org
Note: there is some controversy about the use of __names (see below). Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL. Always decide whether a class’s methods and instance variables (collectively: “attributes”) should be public or non-public.
🌐
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 - # Declare and assign values to variables age = 25 name = "Izabela Gautfrid" is_employee = True salary = 1234.45 # Print the values of variables print("Age:", age) print("Name:", name) print("Is Employee:", is_employee) print("Salary:", salary) ...