0

The following code prints a pattern but I have problem with spacing. I want to print it in a triangle fashion

def triangle(n): 
    s = ""
    for i in range(0,n):
        s +=  "{}".format((i+1)%10)
        j=s*1
        print( s,'*1=',j)


triangle(9)

This is the output I get

1 *1= 1
12 *1= 12
123 *1= 123
1234 *1= 1234
12345 *1= 12345
123456 *1= 123456
1234567 *1= 1234567
12345678 *1= 12345678
123456789 *1= 123456789
rlandster
  • 7,294
  • 14
  • 58
  • 96
shasha
  • 97
  • 1
  • 1
  • 7

1 Answers1

3

If you meen this

         1 * 1 = 1
        12 * 1 = 12
       123 * 1 = 123
      1234 * 1 = 1234
     12345 * 1 = 12345
    123456 * 1 = 123456
   1234567 * 1 = 1234567
  12345678 * 1 = 12345678
 123456789 * 1 = 123456789

then you need ie. {:9s} (for string) to add extra spaces (or {:9d} for int)

def triangle(n): 
    a = 0
    b = 1
    for i in range(1, n+1):
        a = 10*a + i
        print('{:9d} * {} = {}'.format(a, b, a*b))

triangle(9)

See: pyformat.info


EDIT: to use n instead of 9 you need {:{}d} and .format(a, n, ...)

    print('{:{}d} * {} = {}'.format(a, n, b, a*b))

EDIT: version with two arguments

def triangle(n, b): 
    a = 0
    for i in range(1, n+1):
        a = 10*a + i
        print('{:{}d} * {} = {}'.format(a, n, b, a*b))

triangle(5, 3)

    1 * 3 = 3
   12 * 3 = 36
  123 * 3 = 369
 1234 * 3 = 3702
12345 * 3 = 37035

EDIT: some explanations:

Line a = 10*a + i:

You used string and concatenation to create string "1234" from string "123" - "1234" = "123" + "4". I use integer and *10 to create integer 1234 from integer 123 - 1234 = 123*10 + 4. (and now I can use integer 1234 to calcutate 1234*b in next line)

Line print('{:{}d} * {} = {}'.format(a, n, b, a*b))

To make more readable you can use

  • numbers (because arguments in format() are numbered - 0,1,2,...)

    print('{0:{1}d} * {2} = {3}'.format(a, n, b, a*b))
    

    or even (d means decimal or int)

    print('{0:{1:d}d} * {2:d} = {3:d}'.format(a, n, b, a*b))
    
  • names

    print('{x:{y}d} * {z} = {v}'.format(x=a, y=n, z=b, v=a*b))
    

    or even

    print('{x:{y:d}d} * {z:d} = {v:d}'.format(x=a, y=n, z=b, v=a*b))
    

{:9} (or {x:9d}) will get integer value and create 9 char length text aligned to right so you get extra spaces on left side.

Try {:<9} to get 9 char length text aligned to left

1         * 3 = 3
12        * 3 = 36
123       * 3 = 369
1234      * 3 = 3702
12345     * 3 = 37035
123456    * 3 = 370368
1234567   * 3 = 3703701
12345678  * 3 = 37037034
123456789 * 3 = 370370367

or {:^9} to get centered text

    1     * 3 = 3
   12     * 3 = 36
   123    * 3 = 369
  1234    * 3 = 3702
  12345   * 3 = 37035
 123456   * 3 = 370368
 1234567  * 3 = 3703701
12345678  * 3 = 37037034
123456789 * 3 = 370370367

See more: pyformat.info

furas
  • 134,197
  • 12
  • 106
  • 148