Change language

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 = "{: "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 

Python | Filling a string to a fixed length Python functions: Questions

Python | Filling a string to a fixed length String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method