Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

Convert String to Variable in Python: What Works and What to Avoid

A string containing a name is not itself a Python variable. Use a dictionary for runtime-selected values, and reserve globals() for deliberate module-level bindings.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a name chosen at runtime, store the value in a dictionary: use the string as a key, then look up or update that key. A string such as "score" does not automatically become a Python variable name. Use globals() only when you deliberately need to bind a module-level name; avoid exec() for ordinary data storage.

Why a string does not automatically become a variable

In Python, a variable name is a name bound to an object. A string that contains the same characters is still just a string until your code uses it as a namespace key or executes code that refers to that name. For example, name = "score" creates the variable name; it does not create a variable called score.

As an Amazon Associate I earn from qualifying purchases.

When the set of names is selected while a program runs, represent those names as data rather than trying to create identifiers dynamically. The Python programming FAQ and the execution model documentation explain Python’s name-binding and scope rules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a dictionary for runtime-selected names

A dictionary is the clearest way to associate arbitrary string keys with values. The key can come from a variable, a file, an API response, or user input.

name = "score"
values = {}
values[name] = 42
print(values["score"])  # 42

To update or retrieve an entry later, use the same key:

values[name] = 50
print(values[name])  # 50

This approach keeps the data in an explicit container. It also avoids changing the program’s namespace just to hold a value whose label happens to be text.

When a real module-level name is necessary

If another part of a module specifically needs a binding in that module’s global namespace, globals() returns a mapping of the global names. A key in that mapping can be assigned a value:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
name = "score"
globals()[name] = 42
print(score)  # 42, in this module's global namespace

Use this narrowly. Dynamically adding module globals can make code harder to understand and inspect; for values selected at runtime, a dictionary is usually clearer.

Why this does not create a function-local variable

globals() refers to the module namespace, not a function’s ordinary local namespace. Python determines local names from binding operations in a function body. Assigning to a name there makes it local unless the code declares it global or, for a binding in an enclosing function, nonlocal. Reading a local name before it has been assigned can raise UnboundLocalError.

For function-local state whose keys are chosen at runtime, use a local dictionary:

def make_values(name, value):
    values = {}
    values[name] = value
    return values

result = make_values("score", 42)
print(result["score"])  # 42

See the Python execution model for the language’s rules about local and global names.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why not use exec()?

exec() executes Python code supplied as text; it is not a conversion from a string to a variable. Building an assignment statement from a string adds scope complications and can execute unintended code if the text is untrusted. The Python FAQ warns about security risks from dynamic evaluation when a simpler approach will do, and the language reference’s dynamic-features section documents code-execution facilities.

If a name comes from user input, keep it as a dictionary key rather than inserting it into executable Python source. A mapping treats the input as data; code execution treats it as instructions.

Choose the right approach

Approach What it does Best fit
Dictionary, such as values[name] Stores a value under a string key Runtime-selected names and dynamic collections
globals()[name] Binds a name in the module’s global namespace A genuine need for a module-level binding
exec() Executes Python code from text Not ordinary dynamic storage; avoid for this purpose

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.