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
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/
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
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.
Its simple
text = "Au"
name = "Gold"
text.lower() in name.lower()
False
text = "C"
name = "Carbon"
text.lower() in name.lower()
True