【问题标题】:How to Add new line without using \n in python3?如何在 python3 中不使用 \n 添加新行?
【发布时间】:2021-06-23 11:38:45
【问题描述】:

我是初学者,我正在尝试制作一个程序,该程序可以输入名称并以*(星号)模式打印名称, 我定义了函数 A 和 B,它们返回 A 和 B 的 * 模式,但是当我将它们组合起来打印时 他们在新行中打印,我想在同一行中打印它们。我试过打印参数end=''sep='' 但是 它不工作。

def A(size = 10):
    final = str()
    height = size
    breath = size
    
    space1 = breath
    space2 = 1
    
    midline = int(height/2) + 2 #adjust the position of miline
    
    for x in range(1,height+1):
        if x == 1 :
            s = ' '*space1 + '*'
            
        elif x == midline :
            s = ' '*space1 + '*' + '*'*space2 + '*'
            space2 = space2 + 2
            
        else :
            s = ' '*space1 + '*' + ' '*space2 + '*'
            space2 = space2 + 2
        space1 = space1 - 1
        final = final + '\n' + s
    return final

def B(size=10):
    final = str()
    height = size
    breath = size
    space = breath - 2
    curve = 3
    
    for x in range(1,height+1):
        if x == (height//2 + 1):
            s = '*'*(breath - curve)
            s = s + ' '*(breath-len(s))
            
        elif x == 1 or x == height:
            s = '*' * (breath-curve)
            s = s + ' '*(breath-len(s))
            
        elif x == 2 or x == (height-1):
            s = '*'+ ' '*(breath-curve) + '*'
            s = s + ' '*(breath-len(s))
            
        elif x == (height//2 + 1)-1 or x == (height//2 + 1)+1:
            s = '*'+ ' '*(breath-curve) + '*'
            s = s + ' '*(breath-len(s))
            
        else:
            s = '*' + ' '*space + '*'
            s = s + ' '*(breath-len(s))
            
        final = final + '\n' + s
    return final
              
print(B())

【问题讨论】:

  • 您的意思是希望能够将A()B() 的输出组合起来打印“AB”,即彼此相邻?

标签: python python-3.x string replace printing


【解决方案1】:

如果您想像AAAB 一样打印它们,那么您需要更改逻辑。因为当您调用单个 A() 时,python 将使用您使用过的所有 newlines 打印它。您可以执行以下操作

def A(size=10):
    final = str()
    height = size
    breath = size

    space1 = breath
    space2 = 1

    midline = int(height / 2) + 2  # adjust the position of miline

    for x in range(1, height + 1):
        if x == 1:
            s = ' ' * space1 + '*' + ' ' * space1

        elif x == midline:
            s = ' ' * space1 + '*' + '*' * space2 + '*' + ' ' * space1
            space2 = space2 + 2

        else:
            s = ' ' * space1 + '*' + ' ' * space2 + '*' + ' ' * space1
            space2 = space2 + 2
        space1 = space1 - 1
        final = final + '\n' + s
    return final

a1 = A().split('\n')
a2 = A().split('\n')

for i in range(len(a1)):
    print(a1[i] + a2[i])

我在这里修改了A()。在这里,我获取了这封信,然后使用\n 将它们拆分。然后连接每一行并打印。创建字母时,在一行中打印的最后一个星号后使用相同数量的空格。

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2017-07-17
    • 2017-01-28
    • 2021-12-26
    相关资源
    最近更新 更多