TransWikia.com

How to check if a word contains one letter from another string

Stack Overflow Asked by Umar Zahid on February 1, 2021

I am working on a program in which I check if a word for example: "Cat" contains a letter. To this I have tried using if letter in word but it doesn’t work when I try to check for multiple letters in a word as it checks if the word contains every single letter. I have also tried using re like this

import re
bad_letters = "AKS"
word = "Sanctuary"

if re.match(bad_letters, word):
    print("It is a match")

but it doesn’t work.

3 Answers

I believe you wanted to check for bad letters in one string so you could do:

    word = "hello"
    string = "EH"
    for letter in string:
        if letter.lower() in word.lower():
            print('success')
        else:
            print('failure')

Answered by Souhailhimself on February 1, 2021

Here is a regexp solution:

import re
bad_letters = "AKS"
word = "Sanctuary"

if re.search(f"[{bad_letters}]", word, re.IGNORECASE):
    print("It is a match")

It is claimed that it might be slower than avoiding a regexp. In this example, that is indeed true, but only fairly marginally.

$ python3 -mtimeit -s 'bad_letters = "AKSaks"; word = "Sanctuary"' 'any(char in word for char in bad_letters)'
1000000 loops, best of 3: 0.468 usec per loop
$ python3 -mtimeit -s 'bad_letters = "AKS"; word = "Sanctuary"; import re' 're.search(f"[{bad_letters}]", word, re.IGNORECASE)'
1000000 loops, best of 3: 0.622 usec per loop

In fact, some of the time that is measured there is constructing the pattern '[AKS]' from the bad characters 'AKS' and compiling the regexp. If this is taken out of the timing measurement, then the precompiled regexp wins easily.

$ python3 -mtimeit -s 'import re; bad_letters = "AKS"; matcher=re.compile(f"[{bad_letters}]", re.IGNORECASE).search; word = "Sanctuary"' 'matcher(word)'
10000000 loops, best of 3: 0.167 usec per loop

Answered by alani on February 1, 2021

In case you want to also know wich letter match:

bad_letters="AKS".lower()
word="Sanctuary".lower()

for blet in bad_letters:
    for let in word:
        if blet==let:
            print("It is a match:",let)
            break

Answered by David Garcia Ricou on February 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP