[英]Python Printing and multiplying strings in Print statement
I am trying to write a simple python program that prints two ##, then # #, and increases the number of spaces in between the #'s each time. 我正在尝试编写一个简单的python程序,该程序先打印两个##,然后打印##,并每次都增加#之间的空格数。 Here is the code I tried:
这是我尝试的代码:
i=0
while (i<=5):
print ("#" (" " * i) "#")
#print (" " * i)
#print ("#" "#")
The multiplication works in the first line of code I tested then commended out, I see it in the shell each time it prints one more space. 乘法在我测试的第一行代码中起作用,然后被推荐出来,每当它再打印一个空间时,我就会在外壳中看到它。
Printing two #'s works also. 还要印刷两个作品。
I can't figure out how to combine it into one statement that works, or any other method of doing this. 我无法弄清楚如何将其组合成一个有效的语句,或执行此操作的任何其他方法。
Any help would be appreciated, thanks. 任何帮助,将不胜感激,谢谢。
i=0
while (i<=5):
print( "#" +(" "*i)+ "#")
i=i+1
You need to add the strings inside the print statement and increment i. 您需要在print语句中添加字符串,并增加i。
You want to print a string
that depends an a variable. 您要打印一个依赖于变量的
string
。 There are other methods to build a string
but the simplest, most obvious one is adding together some fixed pieces and some computed pieces, in your case a "#"
, a sequence of spaces and another "#"
. 还有其他构建
string
方法,但是最简单,最明显的方法是将一些固定的部分和一些计算的部分加在一起,在您的情况下为"#"
,一系列空格和另一个"#"
。 To add together the pieces you have to use the +
operator, like in "#"+" "+"#"
. 要加在一起,必须使用
+
运算符,例如"#"+" "+"#"
。
Another problem in your code is the while
loop, if you don't increment the variable i
its value will be always 0
and the loop will be executed forever! 代码中的另一个问题是
while
循环,如果不增加变量i
其值将始终为0
,并且循环将永远执行!
Eventually you will learn that the idiom to iterate over a sequence of integers, from 0
to n-1
is for i in range(n): ...
, but for now the while
loop is good enough. 最终,您将了解遍历从
0
到n-1
的整数序列的惯用法是for i in range(n): ...
,但就目前而言, while
循环就足够了。
This should do it: 应该这样做:
i=0
while (i<=5):
print ('#' + i * ' ' + '#')
i = i + 1
Try this: 尝试这个:
def test(self, number: int):
for i in range (number)):
print('#' +i * ''+ '#')
i+=1
return
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.