There are a couple things wrong. First off alphabet
is always being evaluated to "a"
.
The or
in the declaration just means "if the previous thing is false, use this instead." Since "a"
is truthy, it stops there. The rest of the letters aren't even looked at by Python.
Next is the any
. any
just checks if something in an iterable
is true. alphabet + alphabet + alphabet
is being evaluated as "aaa"
, so letter_word_3
always returns True
.
When you check if "ice" == letter_word_3
' it's being evaluated as "ice" == True
.
To check if an arbitrary word is three letters, the easiest way is using the following:
import re
def is_three_letters(word):
return bool(re.match(r"[a-zA-Z]{3}$", word))
You can then use
is_three_letters("ice") # True
is_three_letters("ICE") # True
is_three_letters("four") # False
is_three_letters("to") # False
is_three_letters("111") # False (numbers not allowed)
To also allow numbers, use
import re
def is_three_letters(word):
return bool(re.match(r"[a-zA-Z\d]{3}$", word))
That'll allow stuff like "h2o" to also be considered a three letter word.
EDIT:
import re
def is_three_letters(word):
return bool(re.match(r"[a-z]{3}$", word))
The above code will allow only lowercase letter (no numbers or capitals).
import re
def is_three_letters(word):
return bool(re.match(r"[a-z\d]{3}$", word))
That'll allow only lowercase letters and numbers (no capitals).
EDIT:
To check for n amount of letters, simply change the "{3}" to whatever length you want in the strings in the code above. e.g.
import re
def is_eight_letters(word):
return bool(re.match(r"[a-zA-Z\d]{8}$", word))
The above will look for eight-long words that allow capitals, lowercase, and numbers.
alphabet
? – Malindamalinde