intersection of 2 strings

Cousin Stanley CousinStanley at HotMail.Com
Tue Aug 3 15:54:11 CEST 2004


Antoine Logean wrote:

> Hi,
> 
> What is the easiest way to get the intersection of two strings in
> python (a kind a "and" operator) ?
> ex:
> 
> string_1 =
>
"the_car_of_my_fried_is_bigger_as_mine_but_my_girlfriend_is_more_beautifull"
> 
> string_2 =
> "my_girlfriend_is_more_beautifull_and_has_blue_eyes"
> 
> and the intersection :
> string_1 "and" string_2 = "my_girlfriend_is_more_beautifull"
> 
> thanks for your help
> 

Antoine .... 

  You might try the  sets  module .... 

  The following provides the intersection,
  but I don't know how to maintain the order
  from the original strings ....

sk at cpq1 :  /mnt/win_k/Python/py_Work/Sets  $ python
Python 2.3.4 (#2, Jul  5 2004, 09:15:05)
[GCC 3.3.4 (Debian 1:3.3.4-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> str_1  =
"the_car_of_my_fried_is_bigger_as_mine_but_my_girlfriend_is_more_beautifull"
>>>
>>> str_2  = "my_girlfriend_is_more_beautifull_and_has_blue_eyes"
>>>
>>> list_1 = str_1.split( '_' )
>>> list_2 = str_2.split( '_' )
>>>
>>> import sets
>>>
>>> set_1  = sets.Set( list_1 )
>>> set_2  = sets.Set( list_2 )
>>>
>>> is_12  = set_1.intersection( set_2 )
>>>
>>> print is_12
Set(['girlfriend', 'is', 'my', 'beautifull', 'more'])
>>>

-- 
Cousin Stanley
Human Being
Phoenix, Arizona



More information about the Python-list mailing list