Python split a string by delimiter and trim all elements

Question:

Is there a Python lambda code available to split the following string by the delimiter ">" and create the list after trimming each element?

Input: "p1 > p2 > p3 > 0"

Output: ["p1", "p2", "p3", "0"]

Asked By: Aritra Nayak

||

Answers:

I agree with the comment that all you need is:

>>> "p1 > p2 > p3 > 0".split(" > ")
['p1', 'p2', 'p3', '0']

However, if the whitespace is inconsistent and you need to do exactly what you said (split then trim) then you could use a list comprehension like:

>>> s = "p1 > p2 > p3 > 0"
>>> [x.strip() for x in s.split(">")]
['p1', 'p2', 'p3', '0']
Answered By: RobertB
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.