1

Is there a way to get the same result using .format()?

a = 10
print(f'something {a+2}')
something 12

When I try to do it like this I get KeyError:

print('something {a+2}'.format(a=10))
KeyError                                  
Traceback (most recent call last)
<ipython-input-94-69f36f3c6aec> in <module>
----> 1 'something {a+2}'.format(a=10)

KeyError: 'a+2'

2 Answers2

0

Python 3.8 new feature (Walrus)

a = 10
print(f'something {(result:=a+2)}')

Python 3.7

print(f'something {(a+2)}')
print(f'something {a + 2}')
print('something {a}'.format(a=10 + 2))
print('something {}'.format(a+2))

Updated all above options (Just to match OP's expectations)

drt
  • 735
  • 6
  • 16
0

You may consider this solution: https://stackoverflow.com/a/53671539/4563935

This works for your example:

def fstr(template):
    return eval(f"f'{template}'")

a = 10
template = "something {a + 2}"
print(fstr(template))
# Output: something 12
Ray
  • 170
  • 3
  • 10