When running, sometimes there will be a syntax error: IndentationError: unexpected indent
You can use the following methods to solve:
First display the spaces, where the spaces are replaced by dots
Modify the tab to represent 4 positions
Then the format is aligned.
Example extension:
How to fix text alignment
Hello everyone, I am a newbie in python, and I encountered a problem in an exercise problem.
The requirement of the title is to print out and align the list.
Input data:
tableData =[['apples','oranges','cherries','banana'],['Alice','Bob','Carol','David'],['dogs','cats','moose','goose']]
Required output data (right-aligned first row, left-aligned others):
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
Below is my code
""" Below is the code body"""
tableData =[['apples','oranges','cherries','banana'],['Alice','Bob','Carol','David'],['dogs','cats','moose','goose']]
def printTable(tableData):
# The following is to find the length of the longest string of each inner list
colWidths =[0]*len(tableData)for i inrange(len(colWidths)):
colWidths[i]=len(sorted(tableData[i], key=(lambda x:len(x)))[-1])for x inrange(len(tableData[0])):for y inrange(len(tableData)):print(tableData[y][x].rjust(colWidths[y]), end=' ')print('') #Wrap
printTable(tableData)
The output is (all right aligned):
apples Alice dogs
oranges Bob cats
cherries Carol moose
Recommended Posts