Python 中 print 函数输出多行并且选择对齐方式
代码
# 定义各类别的标签和对应数量
categories = ["class0", "class1", "class2", "class3", "class4", "class5"]
counts = [4953, 547, 5121, 8989, 6077, 4002]# 设置统一的列宽
column_width = 10# 生成对齐后的行,并且用空格连接起来
# < 左对齐
category_line = "".join(f"{cat:<{column_width}}" for cat in categories)
count_line = "".join(f"{count:<{column_width}}" for count in counts)# 打印对齐后的输出
print(category_line)
print(count_line)
输出
.join()
在 Python 中,.join()
是一个字符串方法,用于将可迭代对象(如列表或元组)中的所有元素连接成一个字符串,使用指定的分隔符。常用于将列表中的多个字符串合并为一个字符串。
separator.join(iterable)
- separator:用于连接每个元素的字符串分隔符,常使用空格
" "
或逗号","
- iterable:要连接的字符串序列(如列表或元组)。
words = ["Hello", "world", "from", "Python"]
sentence1 = " ".join(words)
print(sentence1)sentence2 = ",".join(words)
print(sentence2)
f-string
在 Python 的 f-string
中,可以使用不同的对齐方式来格式化字符串。以下是常见的对齐方式:
f"{value:{align}{width}}"
align:对齐方式(<, >, ^)。
- 左对齐 (<):内容左对齐,右侧填充空格。
- 右对齐 (>):内容右对齐,左侧填充空格。
- 居中对齐 (^):内容居中,两侧填充空格。
width:宽度,指定输出的最小字符数。
# 定义变量
value = "Hello"# 左对齐
print(f"{value:<10}") # 'Hello '# 右对齐
print(f"{value:>10}") # ' Hello'# 居中对齐
print(f"{value:^10}") # ' Hello '# 指定其他字符作为填充,比如 - 或 *:
# 左对齐,使用 '-' 填充
print(f"{value:-<10}") # 'Hello-----'# 右对齐,使用 '*' 填充
print(f"{value:*>10}") # '*****Hello'# 居中对齐,使用 '=' 填充
print(f"{value:=^10}") # '==Hello==='