w3resource

Python: Check if a substring presents in a given list of string values

Python List: Exercise - 119 with Solution

Write a Python program to check if a substring appears in a given list of string values.

Visual Presentation:

Python List: Check if a substring presents in a given list of string values.

Sample Solution:

Python Code:

# Define a function 'find_substring' that checks if a substring is present in any of the strings in a list
def find_substring(str1, sub_str):
    # Use a generator expression and 'any' to check if 'sub_str' is in any of the strings in 'str1'
    if any(sub_str in s for s in str1):
        return True
    return False

# Create a list 'colors' with string values
colors = ["red", "black", "white", "green", "orange"]
# Print a message indicating the original list
print("Original list:")
# Print the contents of 'colors'
print(colors)

# Set the substring to search for
sub_str = "ack"
# Print a message indicating the substring to search
print("Substring to search:")
# Print the value of 'sub_str'
print(sub_str)
# Print a message indicating the operation to check for the presence of the substring
print("Check if a substring is present in the said list of string values:")
# Call the 'find_substring' function with 'colors' and 'sub_str', then print the result
print(find_substring(colors, sub_str))

# Set a different substring to search for
sub_str = "abc"
# Print a message indicating the new substring to search
print("Substring to search:")
# Print the value of 'sub_str'
print(sub_str)
# Print a message indicating the operation to check for the presence of the substring
print("Check if a substring is present in the said list of string values:")
# Call the 'find_substring' function with 'colors' and 'sub_str', then print the result
print(find_substring(colors, sub_str)) 

Sample Output:

Original list:
['red', 'black', 'white', 'green', 'orange']
Substring to search:
ack
Check if a substring presents in the said list of string values:
True
Substring to search:
abc
Check if a substring presents in the said list of string values:
False

Flowchart:

Flowchart: Check if a substring presents in a given list of string values.

Python Code Editor:

Previous: Write a Python program to find the difference between elements (n+1th – nth) of a given list of numeric values.
Next: Write a Python program to create a list taking alternate elements from a given list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-119.php