简体   繁体   English

删除开头和结尾的空格,但不要在单词之间

[英]remove leading and trailing spaces but not in between the words

I'm converting a database table into a CSV file with '|' 我正在使用“ |”将数据库表转换为CSV文件 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:- 但是在文件中,我在csv文件中得到了类似的内容:

|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() : 在条形上分割,然后使用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() ). 在这种情况下,无需调用f.close() (尽管您的代码实际上并未调用 f.close() )。 You'll also need to add \\n newlines (as you just stripped the whitespace off). 您还需要添加\\n换行符(因为您刚刚删除了空格)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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