-2

I came across a problem when I was learning python.

print('test%d, %.2f%%' % (1,1.4))

however, it has an error.

ValueError: incomplete format

But if I execute like this:

print('test%d, %.2f%%' % (1,1.4))
test1, 1.40%

It works and prints the '%'. But I don't know why? Can someone help me? Thanks.

Daniel Roseman
  • 541,889
  • 55
  • 754
  • 786
Frederick LI
  • 35
  • 1
  • 5
  • 4
    Those lines appear to be the same. – Daniel Roseman Oct 25 '18 at 13:40
  • It means output a literal `%` sign. – Mark Ransom Oct 25 '18 at 13:40
  • I'll bet your first line was really, `print('test%d, %.2f%' % (1,1.4))`. A single `%` starts a format specifier and *requires* a following format specifier character. How do you then print `%` as a character? You use `%%`. – lurker Oct 25 '18 at 13:41
  • 1
    What material are you using to learn python, because that notation is years out of date... it should be `print('test{:d}, {:.2f}%'.format(1,1.4))` or even better `print(f'test{1}, {1.4:.2f}%')`. It may be worth your while to learn from some more recent materials instead of learning obsolete notation – Dan Oct 25 '18 at 13:42
  • In which case do you get the `ValueError`, if when you run it, it prints OK? – Edgar Ramírez Mondragón Oct 25 '18 at 13:43

2 Answers2

6

Since % is used as a special character in (old C-style) format strings, you have to use %% to print a literal percent sign.

Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
  • 1
    Just a little addition: It's the *old* way to format a string. Nowadays one rather uses [`str.format()`](https://docs.python.org/3.4/library/string.html#string-formatting), see also [PEP-3101](https://www.python.org/dev/peps/pep-3101/). – colidyre Oct 25 '18 at 13:53
  • @colidyre Good point. For anyone writing new code, I would definitely recommend it. – Bill the Lizard Oct 25 '18 at 13:59
1

You need to look into c-style string formatting. %% is a reference to this series of string formatting commands.

The following page: https://docs.python.org/3.4/library/string.html has a "String formatting mini-language" section that answers your question in meticulous detail.

Dylan Brams
  • 1,891
  • 1
  • 17
  • 30