简体   繁体   中英

How do I filter a list of words from a given letter?

I have a python program that I am trying to create where the user can input a letter and the program filters out all the words that do not begin with this letter. Unfortunately me and my beginner brain cannot figure out how to write this in code, so any help?

The code I have already:

#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()
#Take the first character of every word and make a new variable to add that to.
firstchar = [x[0] for x in content]

#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")

Not very much as you can see, but I'm proud of it. I figure I need something that uses firstchar[i] and u_selected to match the two letters together.

As you've done, you can use [0] to access the first character of a string. The below will add each word to a new list for you if it matches the condition specified.

chosen_words = [word for word in content if word.lower()[0] == u_selected.lower()]

The.lower() is to just to convert everything to lower case, to make sure case is ignored

Strings have there own methods to make things easier with strings.

dir(str)

You can test the beginning of a string with.startswith(). For example,

words     = open('Word List').read().splitlines()
new_words = [word for word in words if word.startswith('A')]

To filter that you need to do:

#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()

#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")
filtered_words = [word for word in content if word.startswith(u_selected)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM