如何在Python中不使用第三方模块将二维数组显示为整齐表格
Got it, let's sort out this messy alignment issue without relying on any external modules! The problem with your initial ljust(30) approach is that it treats every character as 1 display width—but Chinese characters, full-width punctuation, and similar symbols actually take up 2 terminal columns. That's why your layout ended up chaotic.
Here's a practical, module-free solution:
Step 1: Calculate Actual Display Width of Strings
First, we need a helper function to compute how many terminal columns a string occupies. This accounts for both narrow (half-width) and wide (full-width) characters:
def get_display_width(s): width = 0 for char in s: # Wide characters (Chinese, full-width symbols) take 2 columns if ord(char) > 127 or char in ['\uFF01', '\uFF0C', '\uFF1A', '\uFF1B', '\uFF1F']: width += 2 # Narrow characters (English, half-width symbols) take 1 column else: width += 1 return width
Step 2: Find Maximum Width for Each Column
Next, we iterate through your results array to find the widest string in each column. This ensures every entry in that column has enough space to align properly:
# Replace this with your actual results array results = [ ["苹果iPhone 14 Pro", "¥7999", "256GB"], ["华为Mate 60 Pro", "¥6999", "512GB"], ["小米14 Ultra", "¥5999", "1TB"], ["三星Galaxy S24 Ultra", "¥8999", "256GB"] ] if not results: print("No data to display") else: # Get number of columns (assuming all rows have same length) column_count = len(results[0]) max_col_widths = [0] * column_count # Calculate max width for each column for col_idx in range(column_count): for row in results: current_width = get_display_width(row[col_idx]) if current_width > max_col_widths[col_idx]: max_col_widths[col_idx] = current_width
Step 3: Align and Print Each Row
Finally, we format each row by padding strings with spaces to match their column's maximum width, then print the result:
# Print aligned rows for row in results: aligned_parts = [] for col_idx in range(column_count): text = row[col_idx] current_width = get_display_width(text) # Calculate how many spaces to add to reach max column width padding = max_col_widths[col_idx] - current_width aligned_parts.append(text + " " * padding) # Join parts with a small gap (optional, adjust as needed) print(" ".join(aligned_parts))
Example Output
Running this code will give you a clean, aligned table like this:
苹果iPhone 14 Pro ¥7999 256GB 华为Mate 60 Pro ¥6999 512GB 小米14 Ultra ¥5999 1TB 三星Galaxy S24 Ultra ¥8999 256GB
You can tweak the get_display_width function to add more full-width symbols if needed, and adjust the spacing between columns by changing the string in " ".join(aligned_parts).
内容的提问来源于stack exchange,提问作者Alexander51413

