Python: Split, strip, and join in one line

44,735

Solution 1

>>> line = 'a: b :c:d:e  :f:gh   '
>>> ','.join(x.strip() for x in line.split(':'))
'a,b,c,d,e,f,gh'

You can also do this:

>>> line.replace(':',',').replace(' ','')
'a,b,c,d,e,f,gh'

Solution 2

Something like?:

>>> L = "1:2:3:4"
>>> result = ",".join([item.strip() for item in L.split(":")])
>>> result
'1,2,3,4'

It takes awhile to get a grasp on list comprehensions. They are basically just packaged loops when you break them down.

So, when learning, try to break it down as a normal loop, and then translate it to a list comprehension.

In your example you don't assign the line variable anywhere, so it would be an error even in a standard loop.

>>> for x in L:
...     items = line.split(":")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'line' is not defined
>>>

Solution 3

Given an string S:

','.join([x.strip() for x in s.split(':')])
Share:
44,735
PandemoniumSyndicate
Author by

PandemoniumSyndicate

Updated on September 13, 2020

Comments

  • PandemoniumSyndicate
    PandemoniumSyndicate almost 4 years

    I'm curious if their is some python magic I may not know to accomplish a bit of frivolity

    given the line:

    csvData.append(','.join([line.split(":").strip() for x in L]))
    

    I'm attempting to split a line on :, trim whitespace around it, and join on ,

    problem is, since the array is returned from line.split(":"), the

    for x in L #<== L doesn't exist!
    

    causes issues since I have no name for the array returned by line.split(":")

    So I'm curious if there is a sexy piece of syntax I could use to accomplish this in one shot?

    Cheers!