[triangle-zpug] how to match strings in python

Chris Calloway cbc at unc.edu
Thu Apr 2 19:27:26 UTC 2009


On 4/2/2009 2:15 PM, Jay Lyerly wrote:
> For the python golfers.....
> 
> a='foobar'
> b='foobaz'
> 
> m=''
> for (x,y) in zip(a,b):  m+= x * (x==y)
> 
> m contains the matching substring.  That's as close to one line as I 
> could get.  :)

Here it is in one line (synthesizing Jay and Chris Rossi's solution with 
a list comprehension:

 >>> "".join([(x*(x==y)) for (x,y) in zip('foobar','foobaz')])
'fooba'
 >>>

-- 
Sincerely,

Chris Calloway
http://www.secoora.org
office: 332 Chapman Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599






More information about the triangle-zpug mailing list