1

I am trying to figure out the syntax for evaluation an expression in Python that involves substituting a variable.

The code needs to go through a list of options, insert string input within the "{:(insert list item here)}"

Example Code (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)) '))

The output should resemble the number 11, in all the possible formats given by the list.

Thank you for everyones help!

sonorhC
  • 25
  • 4
  • `'{:s}'.format(11)` will yield `ValueError: Unknown format code 's' for object of type 'int'` – Faibbus May 24 '18 at 16:21
  • yes, I ran into this as well. Not sure why the number 11 won't be converted to a string. Anyone know? – sonorhC May 24 '18 at 16:46

1 Answers1

1

You can achieve this by splitting in two passages:

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))

If you really want one line, you can use this answer, to have a literal curly bracket in the string, by using double curly brackets '{{':

for atype in formatList:
    print('my number is {{:{}}}'.format(atype).format(n))
FLab
  • 7,136
  • 5
  • 36
  • 69
  • thanks FLab! For those who are new like myself, when I was evaluating FLab's code (which works correctly except for 's', which I've removed), I ran into two problems: The str_template: Notice that there is only one { as this is not an escape sequence/variable (someone correct my terminology please). The second solution, uses double brackets. This seems to be only part of the the format method. Many thanks. – sonorhC May 24 '18 at 16:45