Python中的通用输出格式

在python中打印处理某些数据的结果时,我们可能需要以吸引人的格式或一定的数学精度输出它们。在本文中,我们将看到用于输出结果的不同选项。

使用格式

在这种方法中,我们使用称为format的内置函数。我们将{}用作将由格式提供的值的占位符。默认情况下,位置将使用格式函数中相同的值序列填充。但是我们也可以强制以0开头的位置作为索引的值。

示例

weather = ['sunny','rainy']
day = ['Mon','Tue','Thu']
print('on {} it will be {}'.format(day[0], weather[1]))
print('on {} it will be {}'.format(day[1], weather[0]))
print('on {} it will be {}'.format(day[2], weather[1]))
# 使用占位
print('on {0} it will be {1}'.format(day[0], weather[0]))
print('It will be {1} on {0}'.format(day[2], weather[1]))

运行上面的代码给我们以下结果-

输出结果

on Mon it will be rainy
on Tue it will be sunny
on Thu it will be rainy
on Mon it will be sunny
It will be rainy on Thu

使用%

这种方法更适合于数学表达式。我们可以处理要显示的小数位数或仅打印浮点数的小数部分。我们还可以像科学计数法一样将给定的数字转换为八进制或指数值。

示例

#打印小数
print("Average age is %1.2f and height of the groups %1.3f" %(18.376, 134.219))
#打印整数
print("Average age is %d and height of the groups %d" %(18.376, 134.219))
#
#打印八进制值
print("% 2.7o" % (25))
#打印指数值
print("% 7.4E" % (356.08977))

运行上面的代码给我们以下结果-

输出结果

Average age is 18.38 and height of the groups 134.219
Average age is 18 and height of the groups 134
0000031
3.5609E+02

字符串对齐

我们可以通过使用字符串函数ljust,just或center来对齐作为字符串的输出。除了输入字符串,它们还可以采用另一个用于填充路线的值。

示例

strA = "Happy Birthday !"
# Aligned at center
print(strA.center(40, '~'),'\n')
# Printing left aligned
print(strA.ljust(40, 'x'),'\n')
# Printing right aligned
print(strA.rjust(40, '^'),'\n')

运行上面的代码给我们以下结果-

输出结果

~~~~~~~~~~~~Happy Birthday !~~~~~~~~~~~~
Happy Birthday !xxxxxxxxxxxxxxxxxxxxxxxx
^^^^^^^^^^^^^^^^^^^^^^^^Happy Birthday !