Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding spaces prints the design pattern abnormal in python

I want to print the below pattern

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

My code :

for row in range(1,6):
      print(' ' * (5-row) + row * '*')

The above code gives me expected output but does not add spaces after each *

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

when i am trying to add spaces it is printing as pyramid which is not expected output
any suggestions

print(' ' * (5-row) + row * '* ')  -> space added after `'*  '` 

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

>Solution :

You only need to increase the size of the padding; try the following:

for row in range(1, 6):
    print(' ' * (5 - row) * 2 + row * '* ')
#         *
#       * *
#     * * *
#   * * * *
# * * * * *

Or, you can use f-string with join:

for i in range(1, 6):
    print(f"{' '.join('*' * i):>9}")
#         *
#       * *
#     * * *
#   * * * *
# * * * * *
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading