kahretsinanil
kahretsinanil

Reputation: 1

Python, detect letters with “in”

I’m learning python and got stuck on the “in” keyword. I want to write a simple code which detects the Turkish letters, for example ı,ş,ö,ç,ğ,ü. But my code never find those letters. It always prints ok. What can I do?

usern = input("username:")
if usern in ("ş", "ı", "ö", "ç", "ü", "ğ"):
    print("turkish letter detected")
else:
    print("ok.")

Upvotes: 0

Views: 150

Answers (4)

Óscar López
Óscar López

Reputation: 236112

The membership test is the other way around, and using any() will simplify things. Also, if you want a bit more extra efficiency, you can convert usern into a set object, for faster membership testing:

userset = set(usern)
if any(c in userset for c in ("ş","ı","ö","ç","ü","ğ")):
    ...

Upvotes: 3

Vorashil Farzaliyev
Vorashil Farzaliyev

Reputation: 455

The most time efficient solution would probably be using hash maps.:

from collections import Counter


def has_turkish_letter(word):
    turkish_letters = ["ş", "ı", "ö", "ç", "ü", "ğ"]
    letter_count = Counter(word.lower())
    for letter in turkish_letters:
        if letter_count.get(letter, 0) > 0:
            return True
    return False

if has_turkish_letter(usern):
    print("turkish letter detected")
else:
    print("ok.")

Upvotes: 0

Demetris
Demetris

Reputation: 11

Try this:

usern = input("username:")
chars_list = ["ş", "ı", "ö", "ç", "ü", "ğ"]
print ", ".join([letter for letter in list(usern) if letter in chars_list]])
  1. With list(usern) you convert string to list
  2. Then you check each letter if it's in the defined list of accepted letters.
  3. At the end you print out the found letters.
  4. Better to assign the list/tuple of valid characters in another variable so as to be ale to adjust/handle it easily when needed.

Upvotes: 0

Demetry Pascal
Demetry Pascal

Reputation: 554

Try

usern=input(“username:”)
if any([let in [“ş”,“ı”,”ö”,”ç”,”ü”,”ğ”] for let in usern]):
     print(“turkish letter detected”)
else
    print(“ok.”)

Upvotes: 0

Related Questions