currently I faced issue with python code
I have two questions relate with "def" code.
1) I need to print out 6 alphabet which is "K,E,Y,S,N,O"
slimier like under sample
2) how can I print out this alphabet if user typing one word like "KEY" then print out *mark with KEY or If user typing "BED" then print out "E"only because we only have alphabet with K,E,Y,S,N,O
if can anyone help me with this two questions? I appreciate that
Thanks
CodePudding user response:
Question 1
need work with 2-dimensional list (list with lists for rows) and I skip this problem.
As for Question 2
you can filter chars in word.
You can treat string "BED"
as list of chars (even without using list("BED")
) and you can use it in for
-loop to check every char with list ["K","E","Y","S","N","O"]
(or "KEYSNO"
) and skip chars "B"
and "D"
#my_chars = "KEYSNO" # also works
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
for char in word:
if char in my_chars:
print(char, "- OK")
else:
print(char, "- unknown")
Result:
B - unknown
E - OK
D - unknown
This way you can create new list to keep only correct chars
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
filtered_chars = []
for char in word:
if char in my_chars:
filtered_chars.append(char)
print(filtered_chars)
Result:
['E']
In Python you can write it even shorter using list comprehension
filtered_chars = [char for char in word if char in my_chars]
Eventually you can write it with function filter()
like
filtered_chars = list(filter(lambda char: char in my_chars, word))