- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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)
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']]
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.
- How to split strings on multiple delimiters with Python?
- Python Program to print strings based on the list of prefix
- Maximum occurrence of prefix in the Array in C++
- Program to perform prefix compression from two strings in Python
- Split Concatenated Strings in C++
- Program to find longest common prefix from list of strings in Python
- Program to split two strings to make palindrome using Python
- How to split string on whitespace in Python?
- Python – Split List on next larger value
- Sort tuple based on occurrence of first element in Python
- Python - Prefix sum list
- K Prefix in Python
- Find the longest common prefix between two strings after performing swaps on second string in C++
- Generate two output strings depending upon occurrence of character in input string in Python
- Create a powerful occurrence on the web