Remove Leading And Trailing Spaces But Not In Between The Words
I'm converting a database table into a CSV file with '|' as a delimiter. i have an output of database table like :- Table:- |London | Jul 9 2014 1:21PM |john
Solution 1:
Split on the bars, then strip the results with str.strip()
:
withopen(csv_file, 'w') as f:
for line in table:
line = '|'.join([c.strip() for c in line.split('|')])
f.write(line + '\n')
I'm opening the output file as a context manager here; no need to call f.close()
in that case (although your code doesn't actually callf.close()
). You'll also need to add \n
newlines (as you just stripped the whitespace off).
Demo:
>>>table = '''\...|London | Jul 9 2014 1:21PM |john |...|New York | Jul 9 2014 1:21PM |peter |...|New Zeland | Jul 9 2014 1:21PM |Mr. Jones |...'''.splitlines()>>>for line in table:... line = '|'.join([c.strip() for c in line.split('|')])...print line...
|London|Jul 9 2014 1:21PM|john|
|New York|Jul 9 2014 1:21PM|peter|
|New Zeland|Jul 9 2014 1:21PM|Mr. Jones|
Solution 2:
You can use regex
import re
f = open(csv_file,'w')
for lines in Table:
lines = re.sub(r' *\| *','|',lines) # Remove spaces before and after the pipe character
f.write(lines)
f.close()
Post a Comment for "Remove Leading And Trailing Spaces But Not In Between The Words"