String comparison question

Alex Martelli aleaxit at yahoo.com
Mon Mar 20 05:23:57 CET 2006


Michael Spencer <mahs at telcopartners.com> wrote:

> Olivier Langlois wrote:
> 
> > I would like to make a string comparison that would return true without
> > regards of the number of spaces and new lines chars between the words
> 
> > 
> > like 'A   B\nC' = 'A\nB    C'
> > 
> 
> import string
> NULL = string.maketrans("","")
> WHITE = string.whitespace
> 
> def compare(a,b):
>      """Compare two strings, disregarding whitespace -> bool"""
>      return a.translate(NULL, WHITE) == b.translate(NULL, WHITE)
> 
> Here, str.translate deletes the characters in its optional second argument.
> Note that this does not work with unicode strings.

With unicode, you could do something strictly equivalent, as follows:

nowhite = dict.fromkeys(ord(c) for c in string.whitespace)

and then

  return a.translate(nowhite) == b.translate(nowhite)


Alex



More information about the Python-list mailing list