-1

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
Digi
  • 13
  • 1
  • 3
    you should post at least the code you have tried. You will need to use an `if` and likely an `in` to check if the question mark is in the word........ – Chris Doyle Apr 07 '21 at 14:51

6 Answers6

1

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
0

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")
JD2775
  • 3,658
  • 7
  • 30
  • 52
0

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 == '?']```
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
-1
list = ["Cat", "Bag?", "Dog", "?Duck"]
for i in list:
    if '?' in i:
        print(i, "contains a question mark")
Krossbow
  • 1
  • 1
  • 2
-1
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

  • renamed list to my_list as list is a built-in class in python and overriding it is bad practice
  • used in as pointed out by Brian and Chris
  • used list comprehension to avoid the need for if-clauses as in some of the other answers
CallMeStag
  • 5,467
  • 1
  • 7
  • 22
  • 1
    That is far too complicated for someone trying to just learn how to print strings with a certain character in them – JD2775 Apr 07 '21 at 14:56
  • They can try & understand my answer after understanding yours, though, and that way expand their python skills :) – CallMeStag Apr 07 '21 at 14:58
-1
for string in list:
    if "?" in string:
         echo string + "contains a question mark"
Frightera
  • 4,773
  • 2
  • 13
  • 28
Disco
  • 1