Get common characters from strings

前端 未结 2 739
别跟我提以往
别跟我提以往 2021-02-07 16:12

I\'m looking for the way of comparing two strings and being able to get back, as separate strings:

  • All the common characters,
  • The uncommon characters, (al
相关标签:
2条回答
  • 2021-02-07 16:29

    Use set:

    s = set("123 ABC")
    t = set("135 AZ")
    intersect = s & t # or s.intersection(t)
    exclusion = s ^ t # or s.symmetric_difference(t)
    a_minus_b = s - t # or s.difference(t)
    b_minus_a = t - s # or t.difference(s)
    
    0 讨论(0)
  • 2021-02-07 16:45
    def find_common_characters(msg1,msg2):
        l=[]
        msg11=msg1.replace(" ", "")
        msg22=msg2.replace(" ", "")
        for letter in msg11:
            if letter in msg22:
                l.append(letter)
        if len(l)!=0:
            return "".join(l)
        else:
            return -1
    msg1="I like Python"
    msg2="Java is a very popular language"
    common_characters=find_common_characters(msg1,msg2)
    print(common_characters)   
    
    0 讨论(0)
提交回复
热议问题