String Right-Justification with Padding

  • Share this:

Code introduction


Right-justifies a string in a filled field of a given width, using a specified character for padding.


Technology Stack : Built-in str.zfill() method

Code Type : String formatting

Code Difficulty : Intermediate


                
                    
def zfill(string, width=0, fillchar=' '):
    """
    Right-justify a string in a "filled" field of a given width. The field is filled with the
    specified character (default is a space). The 'fillchar' argument specifies the character
    to use for padding (default is a space). The 'width' argument has the same effect as the
    field width in the format specification in str.format(). If the width is negative or the
    string is longer than the width, the string is returned as is. The string is never
    truncated.
    """
    return string.zfill(width)