Printing of patterns is one of the toughest jobs for the beginners and I am gonna show you how to easily print patterns using some basic concepts of text alignment in python.
In Python, a string of text can be aligned left, right and center by use of following functions.
.ljust(width)
This method returns a left aligned string of length width.
1 2 3 4 | width = 15 print ('Spiderlabweb'.ljust(width,'-') |
Output:
>>Spiderlabweb——-
As you can see that Spiderlabweb is shifted to left by 3 places because length of ‘Spiderlabweb ‘ is 12 and 15-12=3
.center(width)
This method returns a centered string of length width.
1 2 3 4 | >>> width = 16 >>> print 'Spiderlabweb'.center(width,'-') |
Output:
>>–Spiderlabweb–
As you can see that Spiderlabweb is shifted to 2 places to the right and 2 places to the left because 16-12=4 therfore 2 from left and two from right
.rjust(width)
This method returns a right aligned string of length width.
1 2 3 4 | >>> width = 15 >>> print 'Spiderlabweb'.rjust(width,'-') |
Output:
>>—Spiderlabweb
Similar to .ljust(width)
Right Angle Triangle Pattern:
The pattern in which one side is perpendicular to other and here is the code:
1 2 3 4 5 6 | side = int(input()) c = '*' for i in range(side): print((c*(i+1)).ljust(side-1)) |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter a number :10 * ** *** **** ***** ****** ******* ******** ********* ********** |
Inverted Right Angle Triangle Pattern:
The inverted pattern for right angle triangle :
1 2 3 4 5 6 | side = int(input()) c = '*' for i in range(side-1,-1,-1): print((c*(i+1)).ljust(side-1)) |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter a number :10 ********** ********* ******** ******* ****** ***** **** *** ** * |
Isosceles Triangle Pattern:
An isosceles triangle has two sides equal and here is the code for it:
1 2 3 4 5 6 | side = int(input()) c = '*' for i in range(side): print((c*i).rjust(side-1)+c+(c*i).ljust(side-1)) |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter a number : 10 * *** ***** ******* ********* *********** ************* *************** ***************** ******************* |
Inverted Isosceles Triangle Pattern:
The code for it is :
1 2 3 4 5 6 | side = int(input()) c = '*' for i in range(side-1,-1,-1): print((c*i).rjust(side-1)+c+(c*i).ljust(side-1)) |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter a number : 10 ******************* ***************** *************** ************* *********** ********* ******* ***** *** * |
For more Python Examples click on the link below: