Python | Filling a string to a fixed length

Method # 1: Using ljust()

# Python code for demo
# spaces in the line
# to a fixed length

 
# initialization string

ini_string = "123abcjw"

padding_size = 15

 
# print string and its length

print ( "initial string:" , ini_string, len (ini_s tring))

 
# code to fill in spaces in a line

res = ini_string.ljust (padding_size)

 
# print line and its length

print ( "final string:" , res, len (res))

Exit :

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

Method # 2: Using format

# Python code for demonstration
# spaces in the line
# up to fixed length

 
# initializing string

ini_string = "123abcjw"

 
# print line and its length

print ( "initial string:" , ini_string, len (ini_string))

 
# code to fill in spaces in a line

res = "{: & lt; 15}" . format (ini_string)

  # print line and its length

print ( "final string:" , res, len (res))

Output:

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

Method # 3: Using the (* and +) operators

# Python code for demonstration
# line spaces
# to a fixed length

  
# initialization string

ini_string = "123abcjw"

padd ing_size = 15

  
# print line and its length

print ( "initial string:" , ini_string, len (ini_string))

 
# code to fill in spaces in a line

res = ini_string + "" * (padding_size - len (ini_string))

 
# print line and its length

print ( "final string:" , res, len (res))

Exit:

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