Python 字符串周围的边框

1 投票
1 回答
3434 浏览
提问于 2025-04-16 06:18

写一个叫做 spaced(s) 的函数,它可以在字符串 s 周围输出空格和一个虚线边框。

如果你调用 spaced("Hello"),那么输出结果会是:

  --.-.-.-.-
.            .
-   Hello    -
.            .
  -.-.-.-.-.

请帮帮我 :D。我刚开始学习编程,正在努力了解这些东西。我没有任何编程经验,所以对我来说这真是个挑战。谢谢大家!

1 个回答

3

编程的关键在于寻找规律,然后把这些规律应用到实际中。

首先,定义你的需求:
• 必须使用等宽字体
• 上下边框的长度需要等于文本长度加上边距(空白区域)再加上边框的长度
• 文本四周(上下左右)必须留有两个空格
• 你想要交替使用句号和连字符

def spaced(s):
    text = "hello"
    textLength = len(text)
    lineLength = textLength + 2 * (2 + 1)
    height = 5

    # at this point we know the first and fifth lines are the same and
    # we know the first and fourth are the same.  (reflected against the x-axis)

    hBorder = ""
    for c in range(lineLength):
        if c % 2:
            hBorder = hBorder + '.'
        else:
            hBorder = hBorder + '-'
    spacer = "." + " " * (lineLength - 2) + "."
    fancyText = "-  " + text + "  -"
    return (hBorder, spacer, fancyText, spacer, hBorder)

textTuple = spaced("hello world")
for line in textTuple:
    print line

记住,你只能对等宽字体的间距进行预测。如果你对上面的函数有任何疑问,可以在评论区提问。谢谢。

撰写回答