Lets say I have a list of with these strings in it:
list = ["Cat", "Bag?", "Dog", "?Duck"]
How would I print out only the words containing a question mark?
Example output:
Bag? contains a question mark
?Duck contains a question mark
Lets say I have a list of with these strings in it:
list = ["Cat", "Bag?", "Dog", "?Duck"]
How would I print out only the words containing a question mark?
Example output:
Bag? contains a question mark
?Duck contains a question mark
You could use in
like this:
a = ['hi', 'hi?']
for i in a:
if '?' in i:
print(i+' contins a question mark')
Output:
hi? contins a question mark
You shouldn't name your variable "list". That aside, the following would work. Simply use the "in" keyword
list1 = ["Cat", "Bag?", "Dog", "?Duck"]
for i in list1:
if "?" in i:
print(i + " contains a question mark")
I'd try and iterate through each word. Then in each word, I'd iterate through that. If I find a letter, say a "?" then i'll print the word.
your_list = ["?adsd","dsasd"]
for words in your_list:
for every_letter in words:
if every_letter == '?':
print(words)
list comprehension
words_similar = [words for words in your_list for every_letter in words if every_letter == '?']```
list = ["Cat", "Bag?", "Dog", "?Duck"]
for i in list:
if '?' in i:
print(i, "contains a question mark")
my_list = ["Cat", "Bag?", "Dog", "?Duck"]
print('\n'.join(f'{word} contains a question mark' for word in my_list if '?' in word))
Note that I
list
to my_list
as list
is a built-in class in python and overriding it is bad practicein
as pointed out by Brian and Chrisif
-clauses as in some of the other answers