Created
August 27, 2022 16:11
-
-
Save les-peters/624d7cb600d00429e1ef31ffdab2e1a1 to your computer and use it in GitHub Desktop.
Formatted Table String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
question = """ | |
Given a string that represents a markdown table, | |
return a formatted markdown table. A formatted markdown | |
table means that the width of each column is the width of | |
the longest cell in the column. | |
Example: | |
Input: | |
| Syntax | Description | | |
| --- | ----------- | | |
| Header | Title | | |
| Paragraph | Text | | |
Output: | |
| Syntax | Description | | |
| --------- | ----------- | | |
| Header | Title | | |
| Paragraph | Text | | |
""" | |
import re | |
def formattedTable(table): | |
p = re.compile(r'^-+$') | |
table_data = [] | |
row_widths = [] | |
for row in table.split("\n"): | |
table_row = [] | |
i = 0 | |
for col in row.split("|"): | |
col = re.sub(r'^ ', '', col) | |
col = re.sub(r' $', '', col) | |
if col != "": | |
if len(row_widths) <= i: | |
row_widths.append(len(col)) | |
elif row_widths[i] < len(col): | |
row_widths[i] = len(col) | |
m = p.search(col) | |
if m: | |
col = '-' | |
table_row.append(col) | |
i += 1 | |
if table_row != []: | |
table_data.append(table_row) | |
for row in table_data: | |
print("| ", end='') | |
for i in range(0, len(row)): | |
if row[i] == '-': | |
print(row[i] * row_widths[i], end='') | |
else: | |
print(row[i] + " " * (row_widths[i] - len(row[i])), end='') | |
print(" | ", end='') | |
print("") | |
return | |
table = """ | |
| Syntax | Description | | |
| --- | ----------- | | |
| Header | Title | | |
| Paragraph | Text | | |
""" | |
formattedTable(table) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment