在Python中,字符串填充可以通过`str`类的几个方法实现,这些方法允许你控制字符串的对齐和填充方式。以下是几种常见的字符串填充方法:
1. `ljust(width[, fillchar])`:左对齐,指定宽度,如果字符串长度小于宽度,右侧用指定的填充字符填充。
2. `rjust(width[, fillchar])`:右对齐,指定宽度,如果字符串长度小于宽度,左侧用指定的填充字符填充。
3. `center(width[, fillchar])`:居中对齐,指定宽度,如果字符串长度小于宽度,两侧用指定的填充字符填充。
4. `zfill(width)`:右对齐,左侧用0填充,仅指定宽度参数。
示例代码:
text = "hello"
左对齐填充,总宽度为10
print("{:<10}".format(text)) 输出:hello (前面填充空格)
右对齐填充,总宽度为10
print("{:>10}".format(text)) 输出:hello(后面填充空格)
居中对齐填充,总宽度为10
print("{:^10}".format(text)) 输出:hello (两侧填充空格)
左对齐填充,总宽度为10,使用'*'字符
print("{:<10}".format(text, '*')) 输出:hello*(前面填充星号)
右对齐填充,总宽度为10,使用'*'字符
print("{:>10}".format(text, '*')) 输出:*hello (后面填充星号)
居中对齐填充,总宽度为10,使用'*'字符
print("{:^10}".format(text, '*')) 输出:hello(两侧填充星号)