[Tutor] Searching backwards from end of string
Angus Rodgers
angusr at bigfoot.com
Fri Jul 10 17:24:22 CEST 2009
I'm probably having a bit of an off-day, so please forgive me if
this is a really silly question (even for a beginner in Python)!
I'm working through the exercises for Chapter 6 of Wesley Chun's
book [incidentally, I tried to append another endorsement to the
list, but my use of Python rather than "+1" may have looked like
a typo or the work of a lunatic, or perhaps my post is just late
in appearing - anyway, another happy reader here!], and running
again into a difficulty which I "cheated" my way through earlier.
On the earlier occasion:
"6-6 Strings. Create the equivalent of string.strip(): Take a
string and remove all leading and trailing whitespace. (Use of
string.*strip() defeats the purpose of this exercise.)"
I wrote:
from string import whitespace
def lstrip(s):
if s:
for i, c in enumerate(s):
if c not in whitespace:
break
return s[i:]
else:
return s
def rstrip(s):
return lstrip(s[::-1])[::-1]
# Note: far from maximally efficient (two unnecessary copies!)
def strip(s):
return lstrip(rstrip(s))
On the present occasion:
"6-12 Strings. ...
(b) Create another function called rfindchr() that will find the
last occurrence of a character in a string. Naturally this works
similarly to findchr(), but it starts its search from the end of
the input string.
..."
I thought I had better err in the opposite direction, so I wrote:
def findchr(strng, ch):
for i, c in enumerate(strng):
if c == ch:
return i
return -1
def rfindchr(strng, ch):
# Surely there's a neater (but still efficient) way?
n = len(strng)
for i in range(n - 1, -1, -1):
if strng[i] == ch:
return i
return -1
def subchr(strng, origchar, newchar):
chars = list(strng)
for i, c in enumerate(chars):
if c == origchar:
chars[i] = newchar
return ''.join(chars)
I've quoted all my code, in case it's all bad, but it's rfindchr()
that I'm particularly worried about.
--
Angus Rodgers
More information about the Tutor
mailing list