Python | Add leading K character
Sometimes, during the string manipulation, we are into a problem where we need to pad or add leading K to the string as per the requirements. This problem can occur in web development. Having shorthands to solve this problem turns to be handy in many situations. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using rjust()
rjust function offers a single line way to perform this particular task. Hence can easily be employed to any string whose padding we need to be done. We can specify the amount of padding required.
Python3
# Python3 code to demonstrate# Add leading K character# using rjust()# initializing stringtest_string = 'GFG'# printing original stringprint("The original string : " + str(test_string))# No. of zeros requiredN = 4# initializing KK = 'M'# using rjust()# Add leading K characterres = test_string.rjust(N + len(test_string), K)# print resultprint("The string after adding leading K : " + str(res)) |
The original string : GFG The string after adding leading K : MMMMGFG
Method #2 : Using format()
String formatting using the format function can be used to perform this task easily, we just mention the number of elements total, element needed to pad, and direction of padding, in this case left.
Python3
# Python3 code to demonstrate# Add leading K character# using format()# initializing stringtest_string = 'GFG'# printing original stringprint("The original string : " + str(test_string))# No. of zeros requiredN = 4# initializing KK = '0'# using format()# Add leading K character# N for number of elements and '>' for leadingtemp = '{:>' + K + '7}'res = temp.format(test_string)# print resultprint("The string after adding leading K : " + str(res)) |
The original string : GFG The string after adding leading K : 0000GFG
Method #3 : Using replace() method
Python3
# Python3 code to demonstrate# Add leading K character# initializing stringtest_string = 'GFG'# printing original stringprint("The original string : " + str(test_string))# No. of zeros requiredN = 4# initializing KK = 'M'# Add leading K charactertest_string=test_string.replace(test_string[0],K*N+test_string[0],1)# print resultprint("The string after adding leading K : " + str(test_string)) |
The original string : GFG The string after adding leading K : MMMMGFG
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)





Please Login to comment...