Dark horse programmer's python zero-based teaching in the framework of the learning video, the teacher made a business card management system, in which business cards are stored in the form of a dictionary, there is a display all operation about business cards, which is to convert the contents of the dictionaryFormat output like a table.
Operations used in the tutorial:
if card_list: # card_list is the list of stored dictionary cards# print header and dividing linefor name in ["Name", "Phone", "QQ", "Email"]:print(name, end="\t\t")print("")print("=" * 50)for dicts in card_list:print("%s\t\t%s\t\t%s\t\t%s\t\t" % (dicts["name"],dicts["phone"],dicts["qq"],dicts["email"]))
But there will be misaligned results in the actual display results
In the original code, two tabs are added after each output, but the length of the input string is not limited. The short input only takes one tab, and the long one takes two or three.
It is known that a tab character is four spaces. According to the format of the output content, we can also see the law of output with tab characters:
The first tab character \t is special and will be input according to the previous input.The format is determined by the format. If there are less than four spaces, four spaces will be filled, and if there are four spaces, four more spaces will be added.The second \t is to add four spaces directly.
To resolve the need to use a way to fix the input format:
String method format
This method encloses the characters to be replaced in the string with {}
Example:
>>> "{}, {} and {}".format("first","second","third") # Autonumber'first, second and third'>>> "{3} {0} {2} {1} {3} {0}".format("be","not","or","to") # Manual numbering'to be or not to be'>>> "{foo} {} {bar} {}".format(1,2,foo = 3,bar = 4) # field replacement'3 1 4 2'
Where field is being replaced:
Field!+Conversion flag can control the output type
Fields: + padding/width/delimiter/format
Example:
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))π 'π' '\u03c0'>>> print('{a:x^30,.2f}'.format(a=8848))xxxxxxxxxxx8,848.00xxxxxxxxxxxx
Among them:
The first x--fill with x
^, >, <--filling center, left-fill, right-fill
30--width
,--thousand-digit divisionSymbol
.2f - two decimal places after the decimal point
Improved code:
if card_list:# print header and dividing lineprint("{:^4}{:^12}{:^12}{:^24}".format("name", "phone", "qq", "email")) #Display in the center and assign in turncorresponding widthprint("=" * 50)for dicts in card_list:print("{:^4}{:^12}{:^12}{:^24}".format(dicts["name"],dicts["phone"],dicts["qq"],dicts["email"]))
Improved output: