2017-08-09 29 views
0

当卸下空白我有以下代码:使用图示操作者

print(*[((i+1) * '*' + '\n') for i in range(rows)]) 

产生的输出:

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

所需的输出是:

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

与单个敷贴行,这怎么能做到?我尝试使用.strip(' ')像这样:

print(*[((i+1) * '*' + '\n').strip(' ') for i in range(rows)]) 

但它会产生相同的结果。同样的,.replace(' ', '')

回答

2

传递sep参数为空字符串:

>>> print(*[((i+1) * '*' + '\n') for i in range(rows)], sep='') 
* 
** 
*** 
**** 
***** 

或者使用'\n'.join打印前建立字符串:

>>> print('\n'.join((i+1) * '*' for i in range(rows))) 
* 
** 
*** 
**** 
***** 
+0

比我快。 – chthonicdaemon

1

你可以得到你想要的输出两种方式。如果你坚持使用参数扩展(“splat operator”),你可以通过sep=''。或者你可以用join构建你想要的字符串:

print('\n'.join((i+1) * '*' for i in range(rows)))