在Python中,您可以使用格式化字符串(f-string)或`str.format()`方法来设置数字的对齐方式。以下是使用这些方法进行数字对齐的示例:
使用f-string进行对齐
a = 123
b = 4567
c = 89
左对齐
print(f"{a:10}") 宽度为10,右对齐
print(f"{b:^10}") 宽度为10,居中对齐
print(f"{c:^10}") 宽度为10,居中对齐
使用str.format()进行对齐
a = 123
b = 4567
c = 89
左对齐
print("{} and {}".format(a, b)) 默认左对齐
print("{:10s} and {:>10s}".format(a, b)) 宽度为10,右对齐
print("{:^10s} and {:^10s}".format(a, b)) 宽度为10,居中对齐
使用字符串方法进行对齐
a = 123
b = 4567
c = 89
左对齐
print(str(a).ljust(10)) 宽度为10,右对齐
print(str(b).rjust(10)) 宽度为10,右对齐
print(str(c).rjust(10)) 宽度为10,右对齐
使用openpyxl库进行对齐
from openpyxl import load_workbook
from openpyxl.styles import Alignment
path = 'test1.xlsx'
wb = load_workbook(path)
ws = wb['第一个表']
c = ws['B4']
c.alignment = Alignment(horizontal='right', vertical='center')
wb.save('test1.xlsx')
以上示例展示了如何使用不同的方法来设置数字的对齐方式。您可以根据需要选择合适的方法