112k views
3 votes
PYTHON CODE ONLY:

Given the string, s, and the list, lst, associate the variable contains with True if every string in lst appears in s (and False otherwise). Thus, given the string Hello world and the list ["H", "wor", "o w"], contains would be associated with True.

User Nicole Hu
by
3.8k points

2 Answers

5 votes

Final answer:

The question is about creating a Python program that checks if a list of strings is contained within another string. A loop with an inclusion check is used to determine the result, setting a boolean variable accordingly.

Step-by-step explanation:

The student's question pertains to writing a Python code that checks if every string in a given list lst appears in a given string s. To solve this, we can use a loop and the in keyword. Here's the Python code to accomplish this:

contains = True
for item in lst:
if item not in s:
contains = False
break

This code initializes contains as True and iterates over each item in lst. If any item is not found in s, it sets contains to False and breaks out of the loop. After checking all items, contains will correctly reflect whether all elements from lst are contained within s.

User Alex Witsil
by
3.9k points
1 vote

Final answer:

To check if every string in the list lst appears in the string s in Python, you can use the all() function and a list comprehension.

Step-by-step explanation:

In Python, you can use the all() function and a list comprehension to check if every string in the list lst appears in the string s. Here's how you can do it:

  1. Create a variable contains and set it equal to True.
  2. Use the list comprehension [string in s for string in lst] to create a list of boolean values indicating whether each string in lst is present in s.
  3. Pass this list as an argument to the all() function to check if all the boolean values are True.
  4. If the result of all() is False, set contains to False.

Here's the code:

def check_strings(s, lst):
contains = True
if not all([string in s for string in lst]):
contains = False
return contains

s = "Hello world"
lst = ["H", "wor", "o w"]
contains = check_strings(s, lst)
print(contains) # Output: True

User Sasikumar
by
3.7k points