Python Tricks

Use of * in python

ยท

2 min read

Asterisk (*) is commonly used to multiply Integers/Float/Double but in python they are used with Strings, Arrays and Tuples as well.

Let's see how

s = "shy"
print(s*3)

"shyshyshy"

It is very useful while solving pattern designing problems. Let us have a look on the famous Hackerrank challenge 'Designing a Door Mat"

Link to the problem:

hackerrank.com/challenges/designer-door-mat..

Solution:


n,m =map(int, input().split())
      for i in range(n):
      pattern = ".|."
      if i<(n-1)/2:
           print((pattern*(2*i +1)).center(m,"-"))
      elif i==(n-1)/2:
           print("WELCOME".center(m, "-"))
      else:
           print((pattern*(2*(n-1-i)+1)).center(m,"-"))

Now here Asterisk is operating on both integer as well as string If you have looked at the problem mentioned above you have seen that we have to print pattern(.|.) in upper triangular form(๐Ÿ”ผ) surrounded with "-" and then we have to print welcome in the middle surrounded with "-" and then pattern in lowe triangular form (๐Ÿ”ฝ) surrounded with "-" ,so in if condition we are printing the pattern in ๐Ÿ”ผ form by the help of * pattern is being increased by 2i+1 times and it is being placed in center with the help of center() function of string

ย