简体   繁体   中英

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. 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.

You want to print a string that depends an a variable. 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 "#" . 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!

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM