【问题标题】:Unable to remove whitespace using different methods无法使用不同的方法删除空格
【发布时间】: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


【解决方案1】:

首先,我认为您的代码存在一些缩进问题(例如,for line in file_search: 之后,没有缩进)。

其次,这会给你你想要的:

with open("sample.txt", "r") as file_search:
    f = file_search.read()
print([l.replace(" ", "") for l in f.split(",")])

输出(基于您的示例输入行):

['10311', 'CANCELLED/NOTASSIGNED', '', '', '', '', '', '20160817', 'HD', '', '', '\n']

【讨论】:

  • 它有效,谢谢。但是你能告诉我哪里有错误吗?我的代码中没有发现任何错误。
  • @Sliwa,首先,检查缩进错误。第二次尝试使用print 语句,如果您的程序很小,无法调试,另外,我会在使用它之前将file_search 分配给某个变量(我相信这是一个好习惯)。更新了我的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 2021-05-07
  • 2015-02-12
  • 1970-01-01
  • 2016-06-03
相关资源
最近更新 更多