By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,101 Members | 1,335 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,101 IT Pros & Developers. It's quick & easy.

I need help with a loop that replaces a number in a sentence

P: 9
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?

Expand|Select|Wrap|Line Numbers
  1.  
  2. sentence = "I now have a total of % yellow bananas!"
  3.  
  4. for i in range(2,11):
  5.     print sentence %i
  6.  
  7.  
but that gets me an error:
ValueError: unsupported format character 'y' (0x79) at index 9

When I try it with a different sentence:
Expand|Select|Wrap|Line Numbers
  1. sentence = " I have % dogs!"
  2. for i in range(2,11):
  3.     print sentence %i
  4.  
...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!
Sep 5 '14 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
Python is interpreting the "d" in "% d" as a string formatting type specifier. Add an 's' or other appropriate specifier.
Expand|Select|Wrap|Line Numbers
  1. >>> sentence = " I have %s dogs!"
  2. >>> for i in range(2,11):
  3. ...     print sentence % i
  4. ...     
  5.  I have 2 dogs!
  6.  I have 3 dogs!
  7.  I have 4 dogs!
  8.  I have 5 dogs!
  9.  I have 6 dogs!
  10.  I have 7 dogs!
  11.  I have 8 dogs!
  12.  I have 9 dogs!
  13.  I have 10 dogs!
  14. >>>
Sep 6 '14 #2

Post your reply

Sign in to post your reply or Sign up for a free account.