Python 列表理解中的修剪数组元素

Python 列表理解中的修剪数组元素,python,windows,python-2.7,fixed-width,Python,Windows,Python 2.7,Fixed Width,修改了中的代码以将固定宽度数据加载到excel工作表中,但不了解如何修剪函数最后一行中每个数组项的结果 注意-除非打印行被注释掉,否则数据不会加载到excel工作表中 from itertools import tee, izip_longest import openpyxl def fixed_reader(df, data_start, data_end, indices, ws): with open(df, 'rb') as f: for line in ra

修改了中的代码以将固定宽度数据加载到excel工作表中,但不了解如何修剪函数最后一行中每个数组项的结果

注意-除非打印行被注释掉,否则数据不会加载到excel工作表中

from itertools import tee, izip_longest
import openpyxl

def fixed_reader(df, data_start, data_end, indices, ws):
    with open(df, 'rb') as f:
        for line in range(0, data_start): next(f)
        for index, line in enumerate(f):
            if index == data_end: break
            start, end = tee(indices)
            next(end)
            print([line[i:j].rstrip('\r\n') for i,j in izip_longest(start, end)])      # <<<<<
            ws.append([line[i:j].rstrip('\r\n') for i,j in izip_longest(start, end)])  # <<<<<

wb = openpyxl.Workbook()
ws = wb.active
fixed_reader('FixedWidth.dat', 3, 7, [0,1,6,8], ws)
wb.save('FixedWidth.xlsx')

您可以使用
.strip()
从每个字符串的两端修剪空白,或者使用
.strip(“”)
只修剪空白

line = line.rstrip('\r\n')
ws.append([line[i:j].strip(' ') for i,j in izip_longest(start, end)])

能否提供
.dat
文件第一行的预期输出?不太清楚要修剪什么。['K','U','G7','FU046394G']->['K','U','G7','FU046394G'],所以只想删除所有字符串中的所有空白?只修剪每个数组元素两端的空格。
line = line.rstrip('\r\n')
ws.append([line[i:j].strip(' ') for i,j in izip_longest(start, end)])