Python Beginner needs help with for loop

Paul Rubin http
Sun Feb 10 08:23:13 CET 2008

"ty.kresher at" <ty.kresher at> writes:
> Hi, I'm trying to write a for loop in place of the string
> method .replace() to replace a character within a string if it's
> found.

I think you mean you want to replace the last occurrence of the
character in the string, but leave other occurrences intact.

> So far, I've got
> s = raw_input("please enter a string: ")
> c = raw_input("please enter a character: ")

So far so good

> b_s = s[::-1] #string backwards
> found = False #character's existence within the string

I wouldn't bother with this

> for i in range(0,len(s)):

I'd use the built-in rindex function to find the last index:

   loc = s.rindex(c)

Note this will raise an exception if c isn't found.  If you don't
want that, use rfind instead of rindex.  rfind will return -1 and
then you'll have to check for that.

>         print "the last occurrence of %s is in position: " % (c),
>         print (len(s)-i)-1 #extract 1 for correct index

You can put both expressions in the same formatted string:

  print "the last occurrence of %s is in position %d: " % (c, loc)

>     s2 = s.replace(c,"!")
>     print "the new string with the character substituted is: " + s2

s2 = '%s!%s'% (s[:loc], s[loc+1:])

More information about the Python-list mailing list