Python Beginner needs help with for loop

endangeredmassa at gmail.com endangeredmassa at gmail.com
Sun Feb 10 01:52:21 EST 2008


On Feb 10, 12:06 am, "ty.kres... at gmail.com" <ty.kres... at gmail.com>
wrote:
> 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.
>
> So far, I've got
>
> s = raw_input("please enter a string: ")
> c = raw_input("please enter a character: ")
> b_s = s[::-1] #string backwards
>
> found = False #character's existence within the string
>
> for i in range(0,len(s)):
>     if(b_s[i] == c):
>         print "the last occurrence of %s is in position: " % (c),
>         print (len(s)-i)-1 #extract 1 for correct index
>         found = True
>         break #run just once to print the last position
> if found:
>     s2 = s.replace(c,"!")
>     print "the new string with the character substituted is: " +
> s2
>
> I need to replace s2 = s.replace(c,"!") with a for loop function
> somehow.
>
> I don't really see how a for loop would iterate through the string and
> replace the character, and would like to see an example if possible.


s.replace(c,"!") will replace all instances of that character. What
you need to do is just create a new string that equals the old one,
but the target character is replaced with the replacement character.

You don't have to set a flag for "found" at all. You can do it all in
that for loop. Here's an example.

FOR LOOP
  IF MATCH
    CONSTRUCT NEW STRING WITH REPLACEMENT
    SET NEW STRING TO OLD STRING

I can provide actual python code as well.



More information about the Python-list mailing list