Python : 使用 end= 后如何在 for 循环中使用 end= " " 打印新行?



我试图使用for循环打印出列表中客户的记录,但列表中的每一项都在每一行中打印出来。因此,我尝试使用end="quot在同一行打印每一项,但每当打印出最后一列记录时,我如何在下一行打印另一条客户记录?

customer_list = [["ctm1","jaconsdsdsd","ja@gmail.com","+60123954213","15/5/1990"],["ctm2","jactin","jac@gmail.com","+60123237213","15/5/1990"],["ctm3","jactmartin","jacksontai@gmail.com","+60166191111","15/5/1990"]]
# show records of customer account info
def view_customer_account():
# initialize column length
column_length = [2,8,13,12,13]
# loop for longest data length and make it as column length
# column length will remain as initial column length if longest data length is shorter than it
for customer in customer_list:
for i in range(len(column_length)):
if len(customer[i]) > column_length[i]:
column_length[i] = len(customer[i])
# print column name
# column name string will concatenate with a space which multiply with (column length - initial column length)
print(f'| ID{" "*(column_length[0]-2)} | Username{" "*(column_length[1]-8)} | Email Address{" "*(column_length[2]-13)} | Phone number | Date of Birth |')
# print records
# records(str) will concatenate with a space which multiply with (column length/initial column length) - records str length
for customer in customer_list:
for i in range(len(column_length)):
print(f'| {customer[i]+" "*(column_length[i]-len(customer[i]))} ',end="")

view_customer_account()

在不使用end="strong"的情况下输出">

| ID   | Username    | Email Address        | Phone number | Date of Birth |
| ctm1
| jaconsdsdsd
| ja@gmail.com
| +60123954213
| 15/5/1990
| ctm2
| jactin
| jac@gmail.com        
| +60123237213
| 15/5/1990
| ctm3
| jactmartin
| jacksontai@gmail.com
| +60166191111
| 15/5/1990

输出带有end="">

| ID   | Username    | Email Address        | Phone number | Date of Birth |
| ctm1 | jaconsdsdsd | ja@gmail.com         | +60123954213 | 15/5/1990     | ctm2 | jactin      
| jac@gmail.com        | +60123237213 | 15/5/1990     | ctm3 | jactmartin  | jacksontai@gmail.com | +60166191111 | 15/5/1990

预期输出:

| ID   | Username    | Email Address        | Phone number | Date of Birth |
| ctm1 | jaconsdsdsd | ja@gmail.com         | +60166197213 | 15/5/1990     |
| ctm2 | jactin      | jac@gmail.com        | +60166197213 | 15/5/1990     |
| ctm3 | jactmartin  | jacksontai@gmail.com | +60166197213 | 15/5/1990     |

只需在外部循环中添加一个print()语句(不带任何参数(。";最里面的";print添加代码的末尾。

它只会推进";光标";在没有实际打印任何内容的情况下转换为新行。

在内部for循环后添加print('|'),以打印每行的最后一个|字符并插入新行:

for customer in customer_list:
for i in range(len(column_length)):
print(f'| {customer[i] + " " * (column_length[i] - len(customer[i]))} ', end="")
print('|')  # add this one

输出:

| ID   | Username    | Email Address        | Phone number | Date of Birth |
| ctm1 | jaconsdsdsd | ja@gmail.com         | +60123954213 | 15/5/1990     |
| ctm2 | jactin      | jac@gmail.com        | +60123237213 | 15/5/1990     |
| ctm3 | jactmartin  | jacksontai@gmail.com | +60166191111 | 15/5/1990     |

最新更新