如何在带有循环的星形框中打印文本

时间:2019-06-24 14:26:59

标签: python loops for-loop

如何在带有循环的星号框中打印文本

我想要的示例:
input1:输入文字
输入2:满天星斗
例如:
input1 =您的姓名
input2 = 3
输出:

***********
*Your Name*
***********
this my code i have now
def function(text):
    """start"""
    name = len(text)
    num = int(input())
    for i in range(num):
        for j in range(name + 2):
            if i == 0 or j == 0 or i == num - 1:
                print("*", end="")
        print()
function(input())
output is
***********
*
***********

下一步我该怎么做。

4 个答案:

答案 0 :(得分:0)

您可以将一个字符串相乘。 "*" * 10 == '**********'-然后,您不需要内部for循环。

此外,您需要按原样打印东西,而不要先做一个边框-您不能只在已经打印的内容上输入文字。

def function(text):
    """start"""
    name_length = len(text) #renamed your variable, the name was confusing
    num = int(input())
    for i in range(num):
        if i == 0 or i == num - 1: #removed inner loop
            print("*" * (name_length+2))
        else:
            print("*{}*".format(text) #added printing the text and right border
function(input())

您没有说更多的数字会发生什么。我以为这个名字应该重复。

答案 1 :(得分:0)

def function(text):
    """start"""
    name = len(text)
    num = int(input())
    text_num = int((num - 1) / 2)

    for i in range(num):
        for j in range(name + 2):
            if i == 0 or i == num - 1:
                print("*", end="")
            elif i == text_num:
                if j == 0 or j == name + 1:
                    print("*", end="")
                else:
                    print(text[j-1], end="")
        print()
function(input())

答案 2 :(得分:0)

另一个选择是按行而不是字符进行格式化。

类似的事情可能起作用:

const {promisify} = require('util');
const fs = require('fs');
const readFile = promisify(fs.readFile);

const example = async () => {
    const file = await readFile(/*...*/);
}

def function(text): """start""" name = len(text) num = int(input()) for i in range(num): if i == 0 or i == num - 1: print('*' * (name + 2)) elif i == int(num / 2): print('*' + text + '*') else: print('*' + ' ' * name + '*') function(input()) = 3个输出:

num

*********** *your name* *********** = 5个输出:

num

答案 3 :(得分:0)

您可以在列表中构建该框,然后在中间一行替换名称:

name = "your name"
num  = 3

box              = ["*"+(" "*len(name))+"*"]*num
box[0] = box[-1] = "*" * (len(name)+2)
box[num//2]      = f"*{name}*"
print("\n".join(box))

***********
*your name*
***********