如何在python中反转星号三角形 [英] How can I reverse an asterisk triangle in python
本文介绍了如何在python中反转星号三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我有一个代码,可以输出一个星号三角形,如下所示:
Currently, I have a code that outputs an asterisk triangle like this:
*
* *
* * *
* * * *
* * * * *
这是它的代码:
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()
现在,如何使用/修改上面的相同代码,使三角形看起来像这样:
Now, how can I use/modify the same code above to make the triangle look like this:
*
* *
* * *
* * * *
* * * * *
有什么建议吗?
推荐答案
使用字符串方法 str.rjust
:
Using the string method 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
*
* *
* * *
* * * *
* * * * *
这篇关于如何在python中反转星号三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文