首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在使用end='‘时打印两个不同的字符串?

如何在使用end='‘时打印两个不同的字符串?
EN

Stack Overflow用户
提问于 2019-11-03 15:48:21
回答 2查看 36关注 0票数 1

我试图交替打印这两个字符串,但如果不使用end='‘,就无法找到绕过它的方法。我试图使用尽可能小的字符串,我的目标是只使用两个字符串。

代码语言:javascript
运行
复制
num_of_stars = int(input("How many stars would you like on each line?: 
"))
lines1 = 0
lines2 = 0
alternator = 0
def line1(num_of_stars):
    for i in range(num_of_stars):
        print("*", end=' ')
def line2(num_of_stars):
    for i in range(num_of_stars):
        print(" *", end='')
while lines1 <= 4 and lines2 <= 4:
    if alternator == 0:
        line1(num_of_stars)
        lines1 += 1
        alternator = 1
    elif alternator == 1:
        line2(num_of_stars)
        lines2 += 1
        alternator = 0

我的结果是:** *

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-03 16:04:47

你想要什么还不清楚。但是您可能不想使用代码中显示的print( ... , end=...)技术。

分配会简单得多

代码语言:javascript
运行
复制
stars = ['*'] * num_of_stars
line = ' '.join(stars)

然后

代码语言:javascript
运行
复制
for i in range(4):
    indent = ' '[:i % 2]
    print(indent + line)

根据我是偶数还是奇数,indent字符串将为空或空。

票数 1
EN

Stack Overflow用户

发布于 2019-11-07 23:25:25

首先,第2行函数的末尾只是一个空白,这就解释了为什么有2颗恒星的群间隔在一起。试试这个:

代码语言:javascript
运行
复制
num_of_stars = int(input("How many stars would you like on each line?: "))
lines1 = 0
lines2 = 0
alternator = 0
def line1(num_of_stars):
    for i in range(num_of_stars):
        print("*", end="")
    print("\n")
def line2(num_of_stars):
    for i in range(num_of_stars):
        print("*", end="")
    print("\n")
while lines1 <= 4 and lines2 <= 4:
    if alternator == 0:
        line1(num_of_stars)
        lines1 += 1
        alternator = 1
    elif alternator == 1:
        line2(num_of_stars)
        lines2 += 1
        alternator = 0
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58681815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档