Here’s how to do what you say you want. Your description of the desired “table” output is somewhat vague, so I made my best guess.
def get_rows(data):
rows = []
for line in data.splitlines():
fields = line.split(',')
if not any(field == 'NULL' for field in fields): # Not defective row.
rows.append(fields)
return rows
csv_string = 'id,name,age,score\n1,Jack,NULL,12\n17,Betty,28,11'
rows = get_rows(csv_string)
# Find longest item in each column.
widths = [max(len(item) for item in col) for col in zip(*rows)]
# Create a row of separators and make it the second row of the list.
separator_row = [width*'-' for width in widths]
rows.insert(1, separator_row) # Insert following header row.
# Create a format specification for rows of table.
field_specs = [f' {{:{width}}} ' for width in widths]
format_spec="|" + '|'.join(field_specs) + '|'
# Print formatted data.
for row in rows:
print(format_spec.format(*row))
Plain text sample output:
| id | name | age | score |
| -- | ----- | --- | ----- |
| 17 | Betty | 28 | 11 |
2
solved Function to read csv string