Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...