Original List :
['ValueA : 123', 'Source: 10.01, Port: 101, Destination: 10.10', 'ValueB: 4,5,6']
I want to split the value which has multiple ":" and the results should look something like below:
['ValueA : 123', 'Source: 10.01', 'Port: 101', 'Destination: 10.10', 'ValueB: 4,5,6']
Note: This will not always be the second string. This could be anywhere in the list. Basically looking to split a value in the list which has Source, Post and Destination in the same list value.
You could try to split every element in your list, and merge those lists by adding them using
>>> L = ['ValueA : 123', 'Destination: 10.01, Port: 101, Destination: 10.10', 'ValueB: 456'] >>> L = sum( ( # Split only if condition is met element.split(", ") if all(word in element for word in ["Source", "Port", "Destination"]) else [element] for element in L ), start=, ) >>> L
Notice the keyword argument used in
sum(..., start=). By default,
sum() starts with
start=0 because it’s commonly used to add numerical values. In this case, we’re using
sum() to add lists, but
0+ would raise an exception. This is why we must change the start value to a list, an empty list.
Answered By – aaossa
Answer Checked By – Mildred Charles (BugsFixing Admin)