【发布时间】:2019-08-19 16:31:30
【问题描述】:
我正在尝试从基于该文件的列表中删除 file.txt 中的空格。
我尝试了 strip() 和 replace(" ", ""),但都不起作用。我试图避免添加库,使用正则表达式会很容易,但我不知道为什么这些方法不起作用。
这是来自 txt 文件 (Download sample here) 的示例行:
10311,CANCELLED/NOT ASSIGNED , , , , , ,20160817,HD, , ,
我使用的代码:
found_raw = list()
with open("file.txt", "r") as file_search:
for line in file_search:
if no in line:
found_raw.append(line)
for entry in found_raw:
found = entry.split(",")
for item in found:
item.replace(" ", "")
我也尝试过使用 strip()。
for item in found:
item.strip()
结果是一样的:
['222GY', '1142 ', '3980115', '54561', '1990', '7', ' ', 'DR STE 300
', ' ', 'KIRKLAND ', '', '
', 'S', '033', 'US', '20161109', '20110418', '1T ', '5', '5 ', 'V ',
'50364434', ' ', '19930206', '
', ' ', '
', '
', ' ', '20200430', '00994891
', ' ', ' ', 'A1E91C ', '\n']
这就是我想要的:
['222GY', '1142', '3980115', '54561', '1990', '7', '', 'DR STE 300', '','KIRKLAND', '', '', 'S', '033', 'US', '20161109', '20110418', '1T', '5', '5 ', 'V ','50364434', ' ', '19930206', '', '', '', '', '', '20200430', '00994891', '', '', 'A1E91C', '\n']
【问题讨论】:
-
请发布您正在使用的实际 file.txt。另外,您能否使用 Python 安装时应随附的库,例如 csv?
-
我认为这是你出错的地方:
item = item.replace(" ", "") -
文件已上传。我想避免使用 CSV。
-
我也这样做了
print(found[2].isspace())并返回了True。
标签: python-3.x replace split strip removing-whitespace