How to check if letter in a string appear in another string in the same order

后端 未结 4 1840
天命终不由人
天命终不由人 2021-01-16 08:10

I would love to check if the letters from a text appear in another text in the same order.

text    \"Ce\"
name    \"Arsenic\"
Answer   False


for x in te         


        
4条回答
  •  無奈伤痛
    2021-01-16 08:45

    i assume your "in order" means the character match in order. In your example text "Ce" name Arsenic should return False and should return True if text is "eC" instead.

    first we check if all the character are inside the matching text, if yes, we further check if the matching index are in order, else we just return False

    def check_text(text, name):
        name_lower = name.lower()
        if all(x in name_lower for x in text.lower()):
            char_index = [name_lower.index(x) for x in text.lower()]
            return char_index == sorted(char_index)
        else:
            return False
    
    
    >>> check_text("Ce", "Arsenic")
    False
    >>> check_text("eC", "Arsenic")
    True
    

提交回复
热议问题