You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将用户输入字符串转为变量名?Python TypeError报错求助

How to Convert a String to a Corresponding Variable Name in Python

I'm trying to let users input a mobile brand name (as a string), then use that string to access the corresponding dictionary variable to get the model price. Here's my code:

google = { 'Pixel 4' : 64000, 'Pixel 3' : 54000, 'Pixel 2' : 42000, 'Pixel' : 25000 }
iPhone = { '11' : 95000, 'X' : 80000, '7S' : 70000, '7' : 42000 }
print("Mobile Brand = google, iphone")
print(f"{google} \n{iPhone}")
print("Please write the name of brand as mentioned in list")
m = input("Which mobile company do you like? ")
'''When user inputs 'google', it's stored as string 'google' '''
n = str(input(f"Which model of {m} you want to buy? ")) # User inputs Pixel 4
m1 = m.replace("'", "") # Trying to convert 'google' to variable google
print(f"The price of {n} :", m1[n])
'''I expect to get google['Pixel 4'] which outputs 64000, but since m1 is a string, it throws TypeError: string indices must be an integer. Using google[n] directly works, but how can I convert the string to the corresponding variable name?'''

Instead of trying to convert a string to a variable name directly (which is unsafe and not ideal practice), you can create a master dictionary that maps brand names (strings) to their respective dictionaries. This is clean, secure, and easy to maintain.

Here's the revised code:

google = { 'Pixel 4' : 64000, 'Pixel 3' : 54000, 'Pixel 2' : 42000, 'Pixel' : 25000 }
iPhone = { '11' : 95000, 'X' : 80000, '7S' : 70000, '7' : 42000 }

# Create a mapping from brand name strings to their dictionaries
brand_mapping = {
    'google': google,
    'iPhone': iPhone
}

print("Mobile Brand = google, iPhone")
print(f"{google} \n{iPhone}")
print("Please write the name of brand as mentioned in list")
m = input("Which mobile company do you like? ").strip()

# Check if the input brand exists in our mapping
if m not in brand_mapping:
    print(f"Sorry, {m} is not a valid brand.")
else:
    n = input(f"Which model of {m} you want to buy? ").strip()
    selected_brand = brand_mapping[m]
    if n in selected_brand:
        print(f"The price of {n} : {selected_brand[n]}")
    else:
        print(f"Sorry, {n} is not a model of {m}.")

Why This Works:

  • brand_mapping acts as a lookup table: when the user inputs 'google', we use brand_mapping['google'] to get the actual google dictionary directly.
  • We've added error checking to handle invalid brand or model inputs, making the code more robust and user-friendly.

Avoid These Unsafe Methods

While there are ways to convert strings to variables (like using globals() or eval()), they are not recommended because they can execute arbitrary code if the user inputs malicious strings. For example:

  • Using globals()[m][n] might work for your case, but if someone inputs a string like __import__('os').system('rm -rf /'), it could cause serious system damage.
  • eval(m)[n] carries the exact same security risks.

Stick with the mapping dictionary approach—it's the safest and most Pythonic way to solve this problem.

内容的提问来源于stack exchange,提问作者L N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:12:38