Python | Padding a string upto fixed length

Given a string, the task is to pad string up to given specific length with whitespaces. Let’s discuss few methods to solve the given task.

Method #1: Using ljust()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# pad spaces in string
# upto fixed length
  
# initialising string
ini_string = "123abcjw"
padding_size = 15
  
# printing string and its length
print ("initial string : ", ini_string, len(ini_string))
  
# code to pad spaces in string
res = ini_string.ljust(padding_size)
  
# printing string and its length
print ("final string : ", res, len(res))

chevron_right


Output:

initial string :  123abcjw 8
final string :  123abcjw        15

 
Method #2: Using format

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# pad spaces in string
# upto fixed length
  
# initialising string
ini_string = "123abcjw"
  
# printing string and its length
print ("initial string : ", ini_string, len(ini_string))
  
# code to pad spaces in string
res = "{:<15}".format(ini_string)
  
# printing string and its length
print ("final string : ", res, len(res))

chevron_right


Output:

initial string :  123abcjw 8
final string :  123abcjw        15

 
Method #3: Using operators( * and +)

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# pad spaces in string
# upto fixed length
  
# initialising string
ini_string = "123abcjw"
padding_size = 15
  
# printing string and its length
print ("initial string : ", ini_string, len(ini_string))
  
# code to pad spaces in string
res = ini_string + " "*(padding_size - len(ini_string))
  
# printing string and its length
print ("final string : ", res, len(res))

chevron_right


Output:

initial string :  123abcjw 8
final string :  123abcjw        15


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.