22

I'm new to python (and programming in general) and I can't seem to find a solution to this by myself. I want to check the first letter of a string is equal to any letter stored in an array, something like this:

letter = ["a", "b", "c"]
word = raw_input('Enter a word:')
first = word[0]

if first == letter:
    print "Yep"
else:
    print "Nope"

But this doesn't work, does anyone know how it will? Thanks in advance!

ThaRemo
  • 432
  • 1
  • 5
  • 11
  • You have no idea how long I spent on trying to fix this stupid issue and how relieved I was when I found an exact answer on the exact same problem hahahah. – Dat Boi Jul 19 '21 at 10:17

4 Answers4

21

You need to use the in operator. Use if first in letter:.

>>> letter = ["a", "b", "c"]
>>> word = raw_input('Enter a word:')
Enter a word:ant
>>> first = word[0]
>>> first in letter
True

And one False test,

>>> word = raw_input('Enter a word:')
Enter a word:python
>>> first = word[0]
>>> first in letter
False
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
9

The hint is in your question. Use any. This uses a generator expression to check if it is True or False.

any(first == c for c in letter)
squiguy
  • 32,370
  • 6
  • 56
  • 63
  • This question might be marked as duplicate, but it's the first result I found in Google when seeking a quick refresher. IMO, this is the best answer. – alphazwest Jan 21 '18 at 14:47
8

Try using the in keyword:

if first in letter:

On your current code, you are comparing a string character (first which equals the first character in word) to a list. So, let's say my input is "a word". What your code is actually doing is:

if "a" == ["a", "b", "c"]:

which will always be false.

Using the in keyword however is doing:

if "a" in ["a", "b", "c"]:

which tests whether "a" is a member of ["a", "b", "c"] and returns true in this case.

1

The problem as I see it, is that you are asking does a character equal an array. This will always return false.

Try using a loop to check 'first' against each item in 'letter'. Let me know if you need help on figuring out how to do this.

Brian H
  • 1,033
  • 2
  • 9
  • 28