Python – Segregate elements by delimiter


When it is required to segregate elements based on a delimiter,

Example

Below is a demonstration of the same −

my_list = ["89@21", "58@51", "19@61", "11@10", "32@65", "34@45", "87@90", "32@21",'1@345']
print("The list is : " )
print(my_list)

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

my_delimiter = "@"
print("The delimiter is :")
print(my_delimiter)

result_before_delim, result_after_delim = [ele.split(my_delimiter)[0] for ele in my_list],[ele.split(my_delimiter)[1] for ele in my_list]

print("The result containing elements before delimiter is : ")
print(result_before_delim)

print("The result containing elements after delimiter is : ")
print(result_after_delim)

Output

The list is :
['89@21', '58@51', '19@61', '11@10', '32@65', '34@45', '87@90', '32@21', '1@345']
The list after sorting is :
['11@10', '19@61', '1@345', '32@21', '32@65', '34@45', '58@51', '87@90', '89@21']
The delimiter is :
@
The result containing elements before delimiter is :
['11', '19', '1', '32', '32', '34', '58', '87', '89']
The result containing elements after delimiter is :
['10', '61', '345', '21', '65', '45', '51', '90', '21']

Explanation

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

  • It is sorted and displayed on the console again.

  • The value for delimiter is defined and is displayed on the console

  • A list comprehension is used to split the delimiter and check if it present in every element of the list.

  • The string before the delimiter and after the delimiter are displayed on the console.

Updated on: 13-Sep-2021

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements