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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wordone
    New Member
    • Aug 2009
    • 9

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

    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?

    Code:
    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:
    Code:
    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!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Python is interpreting the "d" in "% d" as a string formatting type specifier. Add an 's' or other appropriate specifier.
    Code:
    >>> sentence = " I have %s dogs!"
    >>> for i in range(2,11):
    ... 	print sentence % i
    ... 	
     I have 2 dogs!
     I have 3 dogs!
     I have 4 dogs!
     I have 5 dogs!
     I have 6 dogs!
     I have 7 dogs!
     I have 8 dogs!
     I have 9 dogs!
     I have 10 dogs!
    >>>

    Comment

    Working...