Python – Split Strings on Prefix Occurrence


When it is required to split the strings based on the occurrence of the prefix, two empty lists are defined, and a prefix value is defined. A simple iteration is used along with ‘append’ method.

Example

Below is a demonstration of the same −

from itertools import zip_longest

my_list = ["hi", 'hello', 'there',"python", "object", "oriented", "object", "cool", "language", 'py','extension', 'bjarne']

print("The list is : " )
print(my_list)

my_prefix = "python"
print("The prefix is :")
print(my_prefix)

my_result, my_temp_val = [], []

for x, y in zip_longest(my_list, my_list[1:]):
my_temp_val.append(x)
   if y and y.startswith(my_prefix):
      my_result.append(my_temp_val)
      my_temp_val = []

my_result.append(my_temp_val)

print("The resultant is : " )
print(my_result)

print("The list after sorting is : ")
my_result.sort()
print(my_result)

Output

The list is :
['hi', 'hello', 'there', 'python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']
The prefix is :
python
The resultant is :
[['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']]
The list after sorting is :
[['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']]

Explanation

  • The required packages are imported into the environment.

  • A list of strings is defined and is displayed on the console.

  • The prefix value is defined and is displayed on the console.

  • Two empty lists are defined.

  • The ‘zip_longest’ method is used to combine the list along with same list by omitting the first value in an iteration.

  • The elements are appended to one of the empty list.

  • This list is displayed as the output on the console.

  • This list is again sorted and displayed on the console.

Updated on: 13-Sep-2021

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements