删除 csv 文件中的前导和尾随空格

Rya*_*ott 0 python regex csv string

定义:

str = " a , b,c, hello there ! , my name is +++ , g "

如何删除前导和尾随空格,以便输出:

"a,b,c,hello there !,my name is +++,g"

即输出使得逗号分隔值字符串中的值之间没有前导或尾随空格。

我开始阅读正则表达式?这是使用它的合适情况吗?我将如何完成任务?

ett*_*any 5

您可以使用split(),strip()join()像这样:

','.join([item.strip() for item in my_string.split(',')])
Run Code Online (Sandbox Code Playgroud)

输出:

>>> my_string = " a  , b,c, hello there !   ,   my name is +++ ,  g "
>>> ','.join([item.strip() for item in my_string.split(',')])
'a,b,c,hello there !,my name is +++,g'
Run Code Online (Sandbox Code Playgroud)

解释:

split()用于my_string按分隔符分割,,结果如下表:

>>> my_string.split(',')
[' a  ', ' b', 'c', ' hello there !   ', '   my name is +++ ', '  g ']
Run Code Online (Sandbox Code Playgroud)

strip() 用于从前一个列表的每个项目中删除前导和尾随空格:

>>> [item.strip() for item in my_string.split(',')]
['a', 'b', 'c', 'hello there !', 'my name is +++', 'g']
Run Code Online (Sandbox Code Playgroud)

上面这行叫做列表理解

join() 用于通过连接上述列表的项目来形成最后的结果。