循环中的格式打印

2024-06-28 19:47:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码通过运行循环创建多行数据:

import math x = 65 y = 123 curRow = 0 curCol = 0 maxCol = 2 rows = math.ceil((y-x)/maxCol) while curRow < rows: curCol = 0 printRow = "" while curCol < maxCol: if x < 100: char = (chr(x)) numb = ord(char) hexi = format(ord(char), 'x') printRow += (str(numb)).ljust(1) + hexi.rjust(9) + str(char).rjust(10) + ''.rjust(10) elif x >= 100: char = (chr(x)) numb = ord(char) hexi = format(ord(char), 'x') printRow += str(numb).ljust(1) + hexi.rjust(7) + str(char).rjust(10)+ ''.rjust(10) x += 1 curCol += 1 print(printRow) curRow += 1

但最后三行不正确,结果如下:

65 41 A 66 42 B 67 43 C 68 44 D 69 45 E 70 46 F 71 47 G 72 48 H 73 49 I 74 4a J 75 4b K 76 4c L 77 4d M 78 4e N 79 4f O 80 50 P 81 51 Q 82 52 R 83 53 S 84 54 T 85 55 U 86 56 V 87 57 W 88 58 X 89 59 Y 90 5a Z 91 5b [ 92 5c \ 93 5d ] 94 5e ^ 95 5f _ 96 60 ` 97 61 a 98 62 b 99 63 c 100 64 d 101 65 e 102 66 f 103 67 g 104 68 h 105 69 i 106 6a j 107 6b k 108 6c l 109 6d m 110 6e n 111 6f o 112 70 p 113 71 q 114 72 r 115 73 s 116 74 t 117 75 u 118 76 v 119 77 w 120 78 x 121 79 y 122 7a z

我怎样才能使所有的线都正确地对齐,并以直线结束呢


Tags: formatmathrowscharwhilestrchrord
2条回答

将9替换为8:

printRow +=  (str(numb)).ljust(1) + hexi.rjust(8) + str(char).rjust(10) + ''.rjust(10)

当x>;时,您只给出了错误的宽度;100,它的宽度从2变为3,但是hexi.rjust从9变为7。您可以指定更高的最小宽度,因此它看起来很漂亮。像这样:

printRow += (str(numb)).ljust(4) + hexi.rjust(8) + str(char).rjust(10) + ''.rjust(10)

相关问题 更多 >