简体   繁体   中英

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         |
|New York        |       Jul  9 2014  1:21PM  |peter        |
|New Zeland      |       Jul  9 2014  1:21PM  |Mr. Jones    |

I want to remove the trailing spaces and format it like:-

|London|Jul  9 2014  1:21PM|john|
|New York|Jul  9 2014  1:21PM|peter|
|New Zeland|Jul  9 2014  1:21PM|Mr. Jones|

I'm using following code

f = open(csv_file,'w')
for lines in Table:
    lines = lines.replace(' ','')
    f.write(lines)

f.close

but in the file I'm getting something like this in the csv file:-

|London|Jul920141:21PM|john|
|NewYork|Jul920141:21PM|peter|
|NewZeland|Jul920141:21PM|Mr.Jones|

How can I remove the unwanted spaces and yet keep the onces which are between the words?

Split on the bars, then strip the results with str.strip() :

with open(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 call f.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|

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM