17

My goal with this code is that when you put in a certain number, you will get printed the number and some other output, based on what you typed. For some reason, what I have here gives the error "ValueError: incomplete format". It has something to do with the %. What does the error mean, and how do I fix it? Thanks!

variable = "Blah"
variable2 = "Blahblah"

text = raw_input("Type some stuff: ")

if "1" in text:
    print ("One %" % variable)
elif "2" in text:
    print ("Two %" % variable2)
Lutz Prechelt
  • 36,608
  • 11
  • 63
  • 88
Oughh
  • 302
  • 1
  • 2
  • 10

3 Answers3

24

Python is expecting another character to follow the % in the string literal to tell it how to represent variable in the resulting string.

Instead use

"One %s" % (variable,)

or

"One {}".format(variable)

to create a new string where the string representation of variable is used instead of the placeholder.

Chad S.
  • 6,252
  • 15
  • 25
  • Here is the [Python documentation on this](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) and also a [very nice tutorial](http://www.python-course.eu/python3_formatted_output.php). The tutorial also describes the newer, [``format()`` style of formatting](https://docs.python.org/3/library/string.html#format-string-syntax), but the older ``%`` style is still much used because, although less powerful, it is often more convenient. – Lutz Prechelt Apr 12 '16 at 09:14
13
>>> variable = "Blah"
>>> '%s %%' % variable
    'Blah %'
>>> 
Ravi Gadhia
  • 490
  • 3
  • 11
  • Curious, what version of python did you use for this to work, 3x or 2x? (I am using 2.7.13, where it does not seem to work) – ryyker Jan 13 '17 at 17:53
  • @ryyker, I just tested with Python 3.5.2 - works fine. As far as I can tell it *should* also work for 2.7, according to [this](http://stackoverflow.com/questions/10678229/how-can-i-selectively-escape-percent-in-python-strings). – Aurora0001 Jan 13 '17 at 18:16
  • this doesn't really answer the question but actually solves the problem I had when stumbling upon this question – pocpoc47 Mar 28 '17 at 08:46
1

an easy way:

print ("One " + variable)
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
  • 1
    Or just `print("One", variable)` which works for both strings and non strings, but only in Python 3.x – Artyer Jan 07 '16 at 22:32