Monday, October 3, 2011

difflib

Found another standard library gem: difflib, which allows you to do intelligent string comparisons.

For example:
import difflib
def longest_palindrome(text):
matcher = difflib.SequenceMatcher(None,text,text[::-1])
length = len(text)
a,b,k = matcher.find_longest_match(0,length-1,0,length-1)
return text[a:a+k]
view raw palindrome.py hosted with ❤ by GitHub

will find the longest palindrome in a string, e.g.
>>> from palindrome import *
>>> longest_palindrome('asdfracecarasdf')
'racecar'
>>> longest_palindrome('asdffasdfaipreferpiasdfasdfa')
'aipreferpia'

No comments:

Post a Comment