Python Beginner needs help with for loop

Chris cwitts at gmail.com
Sun Feb 10 04:26:55 EST 2008


On Feb 10, 8: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.

Do the character checking and replacement in the same loop.

s = raw_input("please enter a string: ")
c = raw_input("please enter a character: ")
new_string = ''
replacement_character = '!'
found = False
for each_char in s[::-1]:
    if found:
        new_string += each_char
    elif not found and each_char == c:
        new_string += replacement_character
        found = True
    else:
        new_string += each_char

print 'New string is : %s' % new_string[::-1]

PS: String addition is not the most efficient thing in the world.



More information about the Python-list mailing list