Python 3 - 动态表达式评估

时间:2018-05-24 16:03:42

标签: python-3.x

我试图找出在Python中评估表达式的语法,该表达式涉及替换变量。

代码需要遍历一个选项列表,在“{:(此处插入列表项)}”中插入字符串输入“

示例代码(Python 3.x):

    n = 11
    print("my number is {:d}".format(n))

    formatList = ['e', 'b', 'o', 'd', 'x', 'f', 's']

    for atype in formatList:
        # Failed Attempts:
        # print("my number is {:eval(atype)}".format(n))
        # print("my number is {:" + eval(atype) + "}".format(n))
        # print(eval("my number is {:" + atype + "}").format(n))
        # print(eval(' "my number is {:" + atype + "}".format(n)) '))

输出应该类似于数字11,以列表给出的所有可能格式。

感谢大家的帮助!

1 个答案:

答案 0 :(得分:1)

您可以通过分为两个段落来实现这一目标:

n = 11
print("my number is {:d}".format(n))

formatList = ['e', 'b', 'o', 'd', 'x', 'f', 's']

for atype in formatList:
    str_template = 'my number is {:' + atype + '}'
    print(str_template.format(n))

如果你真的想要一行,你可以使用this回答,在字符串中使用双花括号' {{':

for atype in formatList:
    print('my number is {{:{}}}'.format(atype).format(n))
相关问题