r/codehs • • Jul 12 '22
Python help with 7.5.5
here is my code
word = input("enter word:")
vowel = ["a", "e", "i", "o", "u"]
def contains_vowel():
if vowel in word:
print("True")
else:
print("False")
contains_vowel()when I run it, I get this message:
enter word:hi
Traceback (most recent call last):
File "scratchpad.py", line 10, in <module>
contains_vowel()
File "scratchpad.py", line 5, in contains_vowel
if vowel in word:
TypeError: 'in <string>' requires string as left operand, not listanyone know how to fix this or just the correct way to do it
0
Upvotes
View all comments
Show parent comment
1
u/Wallabanjo Jul 13 '22
Regex isn't a python specific thing, it's used in a ton of different language. To be honest, I am not a python programmer (R and Java mainly) - but I have been programming long enough that I know what to look up. From your description you are looking for specific text elements in a given word - which is exactly the sort of thing Regex (regular expressions) is designed for.
Regex looks at finding how patterns match within text. The "re" library/package is pythons regex library. so it needs to be imported so you can use its functions. "findall" will "find all instances of the search pattern in the target text". So the patter I used is '[aeiou]'. the aeiou is obvious (the vowels). Wrapping it in [ ] says "find any of the characters listed in-between the [ ]. If you were looking for numbers it could be [0123456789] (or better still [0-9]). It's just a lit of characters you are looking for (ie "the pattern to match").
in the example above lets say word is set to "rabbit". re.findall("[aeiou]", word) would return ["a", "i"] (that is, an array containing two elements which are "a" and "i"). len(re.findall("[aeiou]", word)) says "the findall return an array, using len, tell me how long - that is how many elements - are in the returned array). In this case it is 2. So, checking "len(re.findall('[aeiou]', word)) > 0" we check the length of the array (2) and ask is 2 > 0. The result is True.
There is a lot of power in the regex library, and in regex in general.