我的代码:
infile = open("table1.txt", "r")
a_list = infile.read().split("\n")
infile.close()
for pass_num in range(len(a_list)-1, 0, -1):
for i in range(0, pass_num):
if int(a_list[i].split(",")[1].strip()) > int(a_list[i+1].split(",")[1].strip()):
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
if (int(a_list[i].split(",")[1].strip()) == int(a_list[i+1].split(",")[1].strip())) and ((int(a_list[i].split(",")[2]) - int(a_list[i].split(",")[3].strip())) > (int(a_list[i+1].split(",")[2].strip()) - int(a_list[i+1].split(",")[3].strip()))):
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
if (int(a_list[i].split(",")[1].strip()) == int(a_list[i+1].split(",")[1].strip())) and ((int(a_list[i].split(",")[2]) - int(a_list[i].split(",")[3].strip())) == (int(a_list[i+1].split(",")[2].strip()) - int(a_list[i+1].split(",")[3].strip()))):
if (int(a_list[i].split(",")[2])) > int(a_list[i+1].split(",")[2]):
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
a_list.reverse()
print(" Team" + " "*(30-len(" Team")) + "Points" + " "*2 + "Diff" + " "*4 + "Goals")
for i in range(len(a_list)):
team = a_list[i].split(",")[0]
points = a_list[i].split(",")[1]
goalfor = int(a_list[i].split(",")[2].strip())
goalagainst = int(a_list[i].split(",")[3].strip())
diff = goalfor - goalagainst
print(str(i+1).rjust(2) + ". " + '{0:27} {1:4} {2:4} {3:5} : {4:2}'.format(team, points, diff, goalfor, goalagainst))
#Area of interest above^
当前输出:
所需输出:
有人知道如何编辑注释代码段中感兴趣的区域,以产生所需的输出,并将 9 排列在 13 中的 3 下方吗?我一直在尝试 .rjust(1)
但它似乎不起作用。
最佳答案
Python 字符串格式支持 align .
align ::= "<" | ">" | "=" | "^"
'<' Forces the field to be left-aligned within the available space (this is the default for most objects).
'>' Forces the field to be right-aligned within the available space (this is the default for numbers).
'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.
'^' Forces the field to be centered within the available space.
因此使用 {:>}
进行右对齐。
演示
>>> print "{}\t{:<2}".format(1, 20)
1 20
>>> print "{}\t{:<2}".format(1, 2)
1 2
>>> print "{}\t{:>2}".format(1, 2)
1 2
>>> print "{}\t{:>2}".format(1, 20)
1 20
根据您的情况,只需按以下方式对齐格式即可:
print(str(1).rjust(2) + ". " + '{0:27} {1:>4} {2:4} {3:5} : {4:2}'.format("adasd", 1, -12, 1, 2))
^^^
关于python - 字符串输出格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33072707/