Python - Intersectiing strings

前端 未结 6 551
北海茫月
北海茫月 2021-01-18 08:26

Trying to write a for function that takes two strings and returns the characters that intersect in the order that they appear in the first string.

Here\'s what I tri

6条回答
  •  清酒与你
    2021-01-18 08:43

    It looks like your current script should do it if you fix the typo on the fourth line:

    str3 = str3.join(i for i in str1 if i in str2 not in str3)
    

    should be

    str3 = str3.join(i for i in str1 if i in str2 and i not in str3)
    

    I wouldn't recommend using a set for this simpy because they don't guarantee order. Your script is also likely to be faster.

提交回复
热议问题