[triangle-zpug] how to match strings in python

Chris Rossi chris at archimedeanco.com
Thu Apr 2 15:31:43 UTC 2009


A few things you might find useful:

1) Strings can be accessed like arrays: string_1[3] == 'b'

2) Strings can be iterated over:

   for ch in s:
       do something with ch

3) Strings have a "find" method.  They also have a  "startswith" method.
4) For more advanced searching there is the regular expression library
in the "re" module of the standard library.

5) You might find the "zip" built-in useful for iterating over two things at
once:

match = []
for c1,c2 in zip(string_1, string_2):
   if c1 == c2:
        match.append(c1)
   else:
        break
match = "".join(match)

6) I highly recommend David Beazley's book, "Python Essential Reference,"
which has all of this and much, much more.

Chris



On Thu, Apr 2, 2009 at 9:15 AM, Joseph Mack NA3T <jmack at wm7d.net> wrote:

> I've looked in the string methods/functions in the python docs and I can't
> see how to do what I want, which is to find the parts of strings that match.
> eg
>
>
> string_1 = "foobar"
> string_2 = "foobaz"
>
> matched_string = "fooba"
>
> I need to walk along the string(s) 1 char at a time, accepting matching
> letters, till I get a mismatch, when the code exits. I was expecting to be
> able to retrieve chars one at a time from each of the two strings and test
> if the chars were the same.
>
> How do I do this in python?
>
> Thanks Joe
>
> --
> Joseph Mack NA3T EME(B,D), FM05lw North Carolina
> jmack (at) wm7d (dot) net - azimuthal equidistant map
> generator at http://www.wm7d.net/azproj.shtml
> Homepage http://www.austintek.com/ It's GNU/Linux!
>
> _______________________________________________
> triangle-zpug mailing list
> triangle-zpug at starship.python.net
> http://starship.python.net/mailman/listinfo/triangle-zpug
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://starship.python.net/pipermail/triangle-zpug/attachments/20090402/d2c8a6c3/attachment.htm>


More information about the triangle-zpug mailing list