[Tutor] Searching backwards from end of string
Robert Berman
bermanrl at cfl.rr.com
Fri Jul 10 17:57:21 CEST 2009
I think you are looking for a complex solution.
How about the following example:
In [31]: s1='abcdeefghijkl' #find last 'e'
In [32]: s2=s1[::-1] #reverses s1
In [33]: j=s2.find('e') #finds first 'e' in reversed string
In [36]: ind=len(s1)-j-1 #index into s1 where last occurrence of 'e' is
In [37]: ind
Out[37]: 5
In [38]: s1[ind]
Out[38]: 'e'
In [39]: s1
Out[39]: 'abcdeefghijkl' BINGO. Done.
Is that not a bit simpler
Robert
On Fri, 2009-07-10 at 16:24 +0100, Angus Rodgers wrote:
> 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.
More information about the Tutor
mailing list