Search code examples
pythonpython-3.xlistsplitdelimiter

Python split a string by delimiter and trim all elements


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"]


Solution

  • 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']