1.效果
bash
████████████████████
█ █
█ Hello World █
█ █
████████████████████
████████████████████
█ █
█ 你好,Python! █
█ █
████████████████████
████████████████████████████████████████████████████████
█ █
█ 这是一段比较长的测试文本,用来验证自动适配宽度的效果 █
█ █
████████████████████████████████████████████████████████
这是csdn显示异常, 终端打印是对其了的
2.border_display.py
python
# border_display.py
def get_display_width(s):
"""
计算字符串的显示宽度(中文字符占2个宽度,英文字符占1个)
Args:
s (str): 需要计算宽度的字符串
Returns:
int: 字符串的显示宽度
"""
width = 0
for c in s:
if ord(c) > 127: # 中文字符的Unicode编码大于127
width += 2
else:
width += 1
return width
def display_with_border(text, min_width=20, max_width=120):
"""
将指定文本用边框包裹展示,边框宽度自动适配文本长度
Args:
text (str): 需要展示的文本内容
min_width (int): 边框的最小宽度(避免内容过短时边框太窄)
max_width (int): 边框的最大宽度(避免内容过长时边框太宽)
"""
# 计算文本的实际显示宽度
text_width = get_display_width(text)
# 自动计算边框总宽度:取文本宽度+4(左右各留2个空格)、最小宽度的较大值,且不超过最大宽度
SEPARATOR_WIDTH = min(max(text_width + 4, min_width), max_width)
inner_width = SEPARATOR_WIDTH - 2 # 边框内部可显示的宽度
# 生成带边框的内容
print(f"\n{'█' * SEPARATOR_WIDTH}")
print(f"█{' ' * inner_width}█")
# 计算文本左右的填充空格数,让文本居中
padding = (inner_width - text_width) // 2
print(f"█{' ' * padding}{text}{' ' * (inner_width - text_width - padding)}█")
print(f"█{' ' * inner_width}█")
print(f"{'█' * SEPARATOR_WIDTH}\n")
# 模块自测代码(仅在直接运行该文件时执行)
if __name__ == "__main__":
# 测试不同内容的展示效果
display_with_border("Hello World")
display_with_border("你好,Python!")
display_with_border("这是一段比较长的测试文本,用来验证自动适配宽度的效果")