如何在python中反转星号三角形

Lot*_*ice 2 python for-loop

目前,我有一个输出星号三角形的代码,如下所示:

* 
* * 
* * * 
* * * * 
* * * * * 
Run Code Online (Sandbox Code Playgroud)

这是它的代码:

num = int(input("Enter the number of rows: "))
for i in range(1,num+1):
    for j in range(1,i+1):
        print("*",end=' ')
    print()
Run Code Online (Sandbox Code Playgroud)

现在,我如何使用/修改上面相同的代码来使三角形看起来像这样:

        *
      * *
    * * *
  * * * *
* * * * * 
Run Code Online (Sandbox Code Playgroud)

有什么建议?

wim*_*wim 5

使用字符串方法str.rjust

>>> num = int(input("Enter the number of rows: "))
>>> for i in range(1, num + 1):
...     print(" ".join("*" * i).rjust(num * 2))
Enter the number of rows: 5
         *
       * *
     * * *
   * * * *
 * * * * *
Run Code Online (Sandbox Code Playgroud)

  • 你的回答让我很惊讶。我一直使用 2 个循环和一个条件来解决这个问题。 (2认同)