w3resource

Python: Extract specified size of strings from a given list of string values using lambda


Write a Python program to extract a specified size of strings from a given list of string values using lambda.

Sample Solution:

Python Code :

# Define a function 'extract_string' that takes a list of strings 'str_list1' and an integer 'l' as input
def extract_string(str_list1, l):
    # Filter the 'str_list1' to get strings with a length equal to the provided integer 'l'
    result = list(filter(lambda e: len(e) == l, str_list1))
    
    # Return the filtered list of strings
    return result

# Create a list of strings 'str_list1'
str_list1 = ['Python', 'list', 'exercises', 'practice', 'solution']

# Print the original list 'str_list1'
print("Original list:")
print(str_list1)

# Assign an integer 'l' with the length of strings to extract
l = 8

# Print the length of the string to be extracted
print("\nlength of the string to extract:")
print(l)

# Print the strings of the specified length extracted from the list using the 'extract_string' function
print("\nAfter extracting strings of specified length from the said list:")
print(extract_string(str_list1, l))

Sample Output:

Original list:
['Python', 'list', 'exercises', 'practice', 'solution']

length of the string to extract:
8

After extracting strings of specified length from the said list:
['practice', 'solution']

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to sort a given matrix in ascending order according to the sum of its rows using lambda.
Next: Write a Python program to count float number in a given mixed list using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.