when I use print() for string multiplication, it prints out an extra space (" ") at the beginning of each line. Strange. Anyone could explain why?
I was writing a Mario program with python. The program should run like this
$ python mario.py
Height: 4
#
##
###
####
And this is my code
import cs50
while True:
height = cs50.get_int("Height: ")
if height > 0 and height < 9:
break
for i in range(1, height 1):
print( " " * (height - i), "#" * i)
while the result gives me this
~/ $ python mario.py
Height: 4
#
##
###
####
As you can see, each line has additional space in the front which shouldn't even exist.
CodePudding user response:
print separates its arguments with space, your calculations are right but there's an added space. change it to this:
import cs50
while True:
height = cs50.get_int("Height: ")
if height > 0 and height < 9:
break
for i in range(1, height 1):
print( " " * (height - i), "#" * i, sep="")
CodePudding user response:
You can use f-strings:
for i in range(1, height 1):
print(f"{'#'*i: >{height}}")
Output:
Height: 4
#
##
###
####
CodePudding user response:
if you don't want the spaces that comes before the "#" just make the code like this
import cs50
while True:
height = cs50.get_int("Height: ")
if height > 0 and height < 9:
break
for i in range(1, height 1):
print("#" * i)
