Python Beginner needs help with for loop
ty.kresher at gmail.com
ty.kresher at gmail.com
Sun Feb 10 01:06:54 EST 2008
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.
More information about the Python-list
mailing list