![]() |
VOOZH | about |
In Python, when we work with lists of words or phrases, we often need to break them into smaller pieces, called substrings. A substring is a contiguous sequence of characters within a string. Creating a new list of substrings from a list of strings can be a common task in various applications. In this article, we will create a new list of substrings from a list of strings.
Below are some of the ways by which we can create a new list of substrings from the list of strings in Python:
In this example, a list comprehension is employed to create a new list, `substring_list`, containing substrings extracted from each string in the `original_list`. The slicing notation `[s[1:4] for s in original_list]` extracts characters from index 1 to 3 (exclusive) from each string in the original list.
['ppl', 'ana', 'ran']
In this example, a function `extract_substring` is defined to extract a substring from a given string `s`, and the `map()` function is used to apply this function to each element in the `original_list`. The result is a new list, `substring_list`, containing the extracted substrings, which is then printed.
['ppl', 'ana', 'ran']
In this example, a lambda function is applied using the `map()` function to extract substrings `[1:4]` from each string in the `original_list`. The result is a new list, `substring_list`, containing the extracted substrings, which is then printed.
['ppl', 'ana', 'ran']
In this example, a list comprehension with a conditional statement is employed to create a new list, `substring_list`. It extracts substrings `[1:4]` from strings in the `original_list` only if the length of the string is greater than or equal to 4; otherwise, the original string is retained. The resulting list is then printed.
['ppl', 'ana', 'ran']