Python Beginner needs help with for loop
John Machin
sjmachin at lexicon.net
Sun Feb 10 05:28:34 EST 2008
On Feb 10, 8:26 pm, Chris <cwi... at gmail.com> wrote:
> 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:
The "not found and" could be removed; it's quite redundant
> new_string += replacement_character
> found = True
> else:
> new_string += each_char
But don't stop there; the whole contents of the loop could be replaced
by:
if not found and each_char == c:
new_string += replacement_character
found = True
else:
new_string += each_char
More information about the Python-list
mailing list