[triangle-zpug] how to match strings in python
david at handysoftware.com
Thu Apr 2 21:57:20 UTC 2009
On Thu, Apr 02, 2009 at 06:15:05AM -0700, Joseph Mack NA3T 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?
WARNING! Not tested, use at your own risk...
# Set i to index of first char where strings differ
# The hard way:
for i in range(max(len(string_1), len(string_2))):
if i >= min(len(string_1), len(string_2)):
if string_1[i] != string_2[i]:
# The easy way
i = len(os.path.commonprefix([string_1, string_2]))
> 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
Computer Programming is Fun!
Beginning Computer Programming with Python
More information about the triangle-zpug