Python program to split a string by the given list of strings

Python program to split a string by the given list of strings

Let's create a tutorial on how to split a string using a given list of strings.

Objective: We want to split a given string wherever any of the substrings from a list of strings are found.

Example:

Input String: "I love apples, apples are tasty. Oranges are juicy." List of strings: ["apples", "Oranges"] Output: ['I love ', ', ', ' are tasty. ', ' are juicy.'] 

Splitting a String by a List of Strings

Step 1: Import the required libraries.

import re 

We will use the re (regular expression) library, which provides powerful string manipulation capabilities.

Step 2: Define the input data.

input_string = "I love apples, apples are tasty. Oranges are juicy." split_strings = ["apples", "Oranges"] 

Step 3: Create a regular expression pattern from the list of strings. We will join the strings in the list using the | operator, which acts as an OR operator in regular expressions.

pattern = "|".join(map(re.escape, split_strings)) 

The re.escape() function is used to escape any special characters in the strings.

Step 4: Use the re.split() function to split the input string using the created pattern.

result = re.split(pattern, input_string) 

Step 5: Display the result.

print(result) 

The complete program will look like this:

import re # Define the input data input_string = "I love apples, apples are tasty. Oranges are juicy." split_strings = ["apples", "Oranges"] # Create a regex pattern from the list of strings pattern = "|".join(map(re.escape, split_strings)) # Split the input string using the created pattern result = re.split(pattern, input_string) # Display the result print(result) 

Output:

['I love ', ', ', ' are tasty. ', ' are juicy.'] 

With this program, you can easily split a string wherever any of the specified substrings are found. The order in the split_strings list doesn't matter, as the re.split() function will split the string wherever any of the substrings match.


More Tags

gaps-and-islands contextmenu autostart binary-data hql tf-idf nodemon sql-order-by statistics pdf-generation

More Programming Guides

Other Guides

More Programming Examples