mizanur
mizanur

Reputation:

Python printing the word

If any one can help me with Python code: If I input a letter, How can I print all the words start with that word?

Upvotes: 1

Views: 229

Answers (2)

Mariano
Mariano

Reputation: 3018

print [word for word in words if word.startswith(letter)]

Upvotes: 2

csl
csl

Reputation: 11358

There are many ways of doing this, e.g.:

words = ["zwei", "peanuts", "were", "walking", "down", "the", "strasse"]
letter = "w"
output = [x for x in words if x[0] == letter]

The contents of output will be:

['were', 'walking']

Some notes:

  • If the code needs to be fast you should put the wordlist in some kind of tree.
  • If you need more flexibility, you should build a regular expression for matching

Upvotes: 1

Related Questions