Если вы можете предварительно определить ширину столбцов, то вот код для сшивания нескольких заголовков столбцов:
headers = """\
Categ_1 Categ_2 Categ_3 Categ_4
data1 Group Data Data Data Data ( %) Options
"""
col_widths = [24, 10, 10, 11, 9, 10, 10]
# convert widths to slices
col_slices = []
prev = 0
for cw in col_widths:
col_slices.append(slice(prev, prev + cw))
prev += cw
# verify slices
# for line in headers.splitlines():
# for slc in col_slices:
# print(line[slc])
def extract_line_parts(slices, line_string):
return [line_string[slc].strip() for slc in slices]
# extract the different column header parts
parts = [extract_line_parts(col_slices, line) for line in headers.splitlines()]
for p in parts:
print(p)
# use zip(*parts) to transpose list of row parts into list of column parts
header_cols = list(zip(*parts))
print(header_cols)
for header in header_cols:
print(' '.join(filter(None, header)))
Печать:
['', 'Categ_1', 'Categ_2', 'Categ_3', 'Categ_4', '', '']
['data1 Group', 'Data', 'Data', 'Data', 'Data', '( %)', 'Options']
[('', 'data1 Group'), ('Categ_1', 'Data'), ('Categ_2', 'Data'), ('Categ_3', 'Data'), ('Categ_4', 'Data'), ('', '( %)'), ('', 'Options')]
data1 Group
Categ_1 Data
Categ_2 Data
Categ_3 Data
Categ_4 Data
( %)
Options