【问题标题】:Combining two strings to become a variable in python将两个字符串组合成python中的变量
【发布时间】:2017-07-21 04:48:22
【问题描述】:

我想知道您是否可以将变量和字符串组合在一起并在同一行中为其分配一个变量。

choice + "xpos" -= 1

请帮忙

【问题讨论】:

  • @funnyman:你真是个有趣的人。

标签: python string python-3.x variables


【解决方案1】:

IIUC,您想动态创建变量。你可以……有好方法,也有坏方法。

好办法

使用字典。对于您的情况,最好是defaultdict

In [212]: from collections import defaultdict

In [213]: var_dict = defaultdict(int)

In [215]: choice = 'temp_'

In [216]: var_dict[choice + 'xpos'] -= 1

In [217]: var_dict
Out[217]: defaultdict(int, {'temp_xpos': -1})

不好的方式

你也可以使用eval,但我不会告诉你怎么用,因为你不应该使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多