Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

printing - (Python) How to print something in a straight line

I created the 'star' function to print triangle-shape stars.

I want to create 2 triangle stars next to each other like in this image:

image

But my function only prints one triangle star.

Only using 'star' function, How can i make 2 triangle stars?

s = ["*","* *","*****"]
def star(startpoint):   
     print(" "*(startpoint)+str(s[0]))
     print(" "*(startpoint-1)+str(s[1]))
     print(" "*(startpoint-2)+str(s[2]))

def star2(startpoint):
     print(" "*(startpoint)+str(s[0]),end='')
     print(" "*(startpoint+k)+str(s[0]))
     print(" "*(startpoint-1)+str(s[1]),end='')
     print(" "*(startpoint-1+k)+str(s[1]))
     print(" "*(startpoint-2)+str(s[2]),end='')
     print(" "*(startpoint-2+k)+str(s[2]))

I'd really appreciate it if you could help me.

question from:https://stackoverflow.com/questions/65862580/python-how-to-print-something-in-a-straight-line

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't really know how to accomplish that with the star function you provided, but there is a way to greatly simplify the star2 function:

def star(startpoint, num):
    s = ["*", "* *", "*****"]
    print(f"{' ' * startpoint}{s[0]}{' ' * startpoint}" * num)
    print(f"{' ' * (startpoint - 1)}{s[1]}{' ' * (startpoint - 1)}" * num)
    print(f"{' ' * (startpoint - 2)}{s[2]}{' ' * (startpoint - 2)}" * num)

star(3, 2)

Output:

   *      *   
  * *    * *  
 *****  ***** 

A few notes to what changes I made:

  1. The str() wrapper around the s[0], s[1] and s[2] aren't necessary, as each of its elements are already strings, so adding the str() wrapper only decreases efficiency.
  2. It's better to define the s list inside the function, or make it an argument that needs to be passed into the brackets, or risk a bug if the list were to be altered elsewhere in your code.
  3. Use f strings instead of constant concatenations for readability.
  4. Finally, it is possible, but not very necessary for only three values, to use the built-in enumerate() method to iterate through the s list, instead of hard-coding its indices:
def star(startpoint, num):
    s = ["*", "* *", "*****"]
    for i, v in enumerate(s):
        print(f"{' ' * (startpoint - i)}{v}{' ' * (startpoint - i)}" * num)

star(3, 2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...