Python | Padding a string upto fixed length

Python | Padding a string upto fixed length

In Python, you can pad a string to a fixed length using several methods. Here are some of the most common methods to pad a string:

  1. Using str.ljust() and str.rjust():

    • ljust(): Left justifies the string and pads with specified character (default is space).
    • rjust(): Right justifies the string and pads with a specified character (default is space).
    s = "hello" padded_left = s.ljust(10) # "hello " padded_right = s.rjust(10) # " hello" 

    If you want to pad with a character other than space, you can provide it as the second argument:

    padded_left = s.ljust(10, '*') # "hello*****" padded_right = s.rjust(10, '*') # "*****hello" 
  2. Using str.center():

    This method will center the string and pad with the specified character on both sides:

    s = "hello" centered = s.center(10) # " hello " 

    If you want to pad with a character other than space:

    centered = s.center(10, '*') # "**hello***" 
  3. Using Python f-string (Python 3.6+):

    s = "hello" padded_left = f"{s:<10}" # "hello " padded_right = f"{s:>10}" # " hello" centered = f"{s:^10}" # " hello " 

    To pad with a specific character:

    padded_left = f"{s:*<10}" # "hello*****" padded_right = f"{s:*>10}" # "*****hello" centered = f"{s:*^10}" # "**hello***" 
  4. Using str.format():

    s = "hello" padded_left = "{:<10}".format(s) # "hello " padded_right = "{:>10}".format(s) # " hello" centered = "{:^10}".format(s) # " hello " 

    To pad with a specific character:

    padded_left = "{:*<10}".format(s) # "hello*****" padded_right = "{:*>10}".format(s) # "*****hello" centered = "{:*^10}".format(s) # "**hello***" 
  5. Using zfill() for padding zeros:

    This is useful if you want to pad a string with leading zeros:

    s = "42" padded = s.zfill(5) # "00042" 

Choose the method that you find most readable or that fits your particular use case.


More Tags

is-empty testcafe svg ms-office hibernate-types coronasdk lit-element browser-testing prolog stm32

More Programming Guides

Other Guides

More Programming Examples