Hi,

If I have a sentence like this:

"I now have a total of % yellow bananas!"

but I need it to change the number 2 to a 3, print, then a 4, print, etc until it reaches a set number like 10, how can I go about that?

sentence = "I now have a total of % yellow bananas!"

for i in range(2,11):
    print sentence %i

but that gets me an error:
ValueError: unsupported format character 'y' (0x79) at index 9

When I try it with a different sentence:

sentence = " I have % dogs!"
for i in range(2,11):
    print sentence %i

...it almost works:
I have 2ogs!
I have 3ogs!
I have 4ogs!
I have 5ogs!
I have 6ogs!
I have 7ogs!
I have 8ogs!
I have 9ogs!
I have 10ogs!

Or am I going about this totally the wrong way? Any suggestions? Thanks

The conversion specifier is not the single character %. It has 7 components, most of them optional, as described in the documentation: click here.

So, for example %s and %d are valid conversion specifiers.

Like Dr. Griboullis says, this will work:

sentence = "I now have a total of %s yellow bananas!"

for i in range(2, 11):
    print sentence % i

You can also use the newer syntax available with Python 2.7 and Python3+ ...

sentence = "I now have a total of {} yellow bananas!"

for i in range(2, 11):
    print(sentence.format(i))

Thanks all, for the suggestions!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.