[triangle-zpug] how to match strings in python
philip at semanchuk.com
philip at semanchuk.com
Thu Apr 2 15:43:35 UTC 2009
Quoting Joseph Mack NA3T <jmack at wm7d.net>:
> 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.
And did you find that this expectation failed you? The code below
works, but it assumes that you want to match from the first character
onwards. I'm not sure I adequately understand what you're trying to do.
string_1 = "foobar"
string_2 = "foobaz"
max_length = min(len(string_1), len(string_2))
matches = [ ]
i = 0
done = False
while not done:
if i < max_length:
if string_1[i] == string_2[i]:
matches.append(string_1[i])
else:
done = True
else:
done = True
i += 1
print ''.join(matches)
More information about the triangle-zpug
mailing list