-1
a = 19/3 
print('just testing {a:1.4f}'.format (a))

In python 3.5 this results in an error KeyError: 'a'.
I cannot understand why. I can use a workaround to overcome the error but I would really appreciate if somebody could explain why am I getting the error.

abc
  • 11,579
  • 2
  • 26
  • 51
Ana-Maria
  • 19
  • 4

3 Answers3

1

Dict-like notation:

>>> a = 4
>>> b = 10
>>> 'just testing {num1}, {num2}'.format(num1 = a, num2 = b)
just testing 4, 10

Sequencial notation

>>> a = 4
>>> b = 10
>>> 'just testing {0}, {1}'.format(a, b)
just testing 4, 10

Either use the dict-like notation: print('just testing {num}'.format(num=a)) or the sequential one: print('just testing {0}'.format(a))

Chris
  • 86
  • 5
0
print('just testing {0:.4f}'.format (a))

here the indexing for the variables start with 0. So if you had another variable Let's say b=3.142 the syntax would be :

print('just testing {1:.2f} {0:.4f}'.format (a,b))
Vishal R
  • 1,279
  • 1
  • 21
  • 27
0

the item before the colon is an index into the arguments of the format() function. See https://docs.python.org/3.5/library/stdtypes.html#str.format for more details.

So your example should read:

a = 19/3
print('just testing {0:.4f}'.format (a))

Alternatively, if you are running python 3.6 or above, you can use f-strings:

a = 19/3
print(f'just testing {a:.4f}')

See https://docs.python.org/3/reference/lexical_analysis.html#f-strings for details

Rob Buckley
  • 708
  • 4
  • 16