Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Split, strip, and join in one line

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!

like image 237
PandemoniumSyndicate Avatar asked Sep 12 '12 04:09

PandemoniumSyndicate


People also ask

How do you split and join together in Python?

the split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator.

How do you split a space and a new line in Python?

Use split() method to split by delimiter. If the argument is omitted, it will be split by whitespace, such as spaces, newlines \n , and tabs \t . Consecutive whitespace is processed together. A list of the words is returned.

Is input () Strip () split?

what does input(). strip(). split(' ') in python means?? input() - takes input from user strip() - deletes white spaces from the begin and the end of input split(' ') - splits input into elements of an list with (' ') being as separator.


1 Answers

>>> 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'
like image 195
Burhan Khalid Avatar answered Sep 29 '22 10:09

Burhan Khalid