我试图用python创建一个简单的程序,我想以简单的表格格式显示输出。但是每次对齐都会受到干扰。限制是不要使用Python的format()
。
我正在尝试在python中使用字符串格式打印所需的输出。但是我无法获得所需的输出。请帮助我。
我已经尝试过:
def footToMeter(foot):
Meter = 0.305 * foot
return Meter
def meterToFoot(meter):
Foot = meter / 0.305
return Foot
i = 1.0
j = 20.0
header = ('Feet','Meters | ','Meters','Feet')
print("%-14s%-15s%-15s%-15s" % header)
while i<=15:
print("%s" % i ,"%15.3f" % footToMeter(i)," | ",j,"%16.3f" %
meterToFoot(j))
i = i + 1
j = j + 6
实际输出应采用完全左对齐的表格格式(请检查以下输出)。但是我的输出对齐会受到一些干扰。
答案 0 :(得分:2)
您可以使用标签\t
并使用空格和格式字符串来正确显示,
def footToMeter(foot):
return 0.305 * foot
def meterToFoot(meter):
return meter / 0.305
i = 1.0
j = 20.0
#Replaced spaces with a mix of tabs and spaces
print('Feet\t\t Meters\t\t|\t\t Meters\t\tFeet')
print()
while i<=15:
#Played around with format strings
print("%-4.1f\t\t" % i ,"%-.3f" % footToMeter(i),"\t\t|\t\t",j,"\t\t%-7.3f" %meterToFoot(j))
i = i + 1
j = j + 6
这给了我桌子
Feet Meters | Meters Feet
1.0 0.305 | 20.0 65.574
2.0 0.610 | 26.0 85.246
3.0 0.915 | 32.0 104.918
4.0 1.220 | 38.0 124.590
5.0 1.525 | 44.0 144.262
6.0 1.830 | 50.0 163.934
7.0 2.135 | 56.0 183.607
8.0 2.440 | 62.0 203.279
9.0 2.745 | 68.0 222.951
10.0 3.050 | 74.0 242.623
11.0 3.355 | 80.0 262.295
12.0 3.660 | 86.0 281.967
13.0 3.965 | 92.0 301.639
14.0 4.270 | 98.0 321.311
15.0 4.575 | 104.0 340.984
答案 1 :(得分:1)
您可以使用f-strings。从Python3.6起可以使用它们。
如
i = 1.0
j = 20.0
header = ('Feet','Meters')
print (f"{header[0]:<10}{header[1]:<10s} | {header[1]:<10s}{header[0]:<10s}\n")
while i<=15:
print(f"{i:<10.1f}{footToMeter(i):<10.3f} | {j:<10.1f}{meterToFoot(j):<10.3f}")
i = i + 1
j = j + 6
获得类似的输出
Feet Meters | Meters Feet
1.0 0.305 | 20.0 65.574
2.0 0.610 | 26.0 85.246
3.0 0.915 | 32.0 104.918
4.0 1.220 | 38.0 124.590
5.0 1.525 | 44.0 144.262
6.0 1.830 | 50.0 163.934
7.0 2.135 | 56.0 183.607
8.0 2.440 | 62.0 203.279
9.0 2.745 | 68.0 222.951
10.0 3.050 | 74.0 242.623
11.0 3.355 | 80.0 262.295
12.0 3.660 | 86.0 281.967
13.0 3.965 | 92.0 301.639
14.0 4.270 | 98.0 321.311
15.0 4.575 | 104.0 340.984
<
用于左对齐。
对header
元组和字段宽度进行了修改。
您可能也对PEP感兴趣。
答案 2 :(得分:0)
对代码的最小更改将是
old: print( "%s" % i ,"%15.3f" % footToMeter(i)," | ", j,"%16.3f" % meterToFoot(j))
new: print("%4d" % i ,"%15.3f" % footToMeter(i)," |","%9d" % j,"%12.3f" % meterToFoot(j))
所以关键是要使所有内容都具有固定的宽度(i
和j
在原始位置没有宽度),然后这只是数字的玩法({{1} }甚至都没有改变。)
结果如下:
%15.3f
您可以在此处查看它的运行情况:https://ideone.com/9UKuw1
Feet Meters | Meters Feet
1 0.305 | 20 65.574
2 0.610 | 26 85.246
3 0.915 | 32 104.918
4 1.220 | 38 124.590
5 1.525 | 44 144.262
6 1.830 | 50 163.934
7 2.135 | 56 183.607
8 2.440 | 62 203.279
9 2.745 | 68 222.951
10 3.050 | 74 242.623
11 3.355 | 80 262.295
12 3.660 | 86 281.967
13 3.965 | 92 301.639
14 4.270 | 98 321.311
15 4.575 | 104 340.984
尽管我认为结果(左对齐)很丑:
old: print( "%s" % i ,"%15.3f" % footToMeter(i)," | ", j, "%16.3f" % meterToFoot(j)) new: print("%-13d" % i ,"%-9.3f" % footToMeter(i),"| ","%-14d" % j,"%-12.3f" % meterToFoot(j))
或者在https://ideone.com/RatzqW上查看它的运行情况