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

后端 未结 4 1841
天命终不由人
天命终不由人 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:42

    Essentially, you want to check if text is contained in name. So instead of doing it at the character by character level (i.e. if all characters in text appears in name, the way that you are doing now), use the in operator on the two strings to check if text is in name.

    i.e. return text.lower() in name.lower()

    see https://www.pythoncentral.io/how-to-see-if-a-string-contains-another-string-in-python/

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-16 08:46

    One way to do it would be to avoid iterating through each letter of the word.

    if any(text in name for text in text_collection):
        print(text)
    

    This would check the whole string of text against a string in name. This is assuming that text_collection has more than one entry. Otherwise just use if any(text in name): See the official documentation of any here.

    0 讨论(0)
  • 2021-01-16 08:46

    Its simple

    text = "Au"
    name = "Gold"
    text.lower() in name.lower()
    False
    
    text = "C"
    name = "Carbon"
    text.lower() in name.lower()
    True
    
    0 讨论(0)
提交回复
热议问题