Python string alignment zfill method

Python String Alignment zfill Method

Description

The zfill() method pads a string with zeros on the left to a specified width.

Syntax

The following is the syntax of the zfill() method:

var.zfill(width)

Parameters

  • width: This is the final width of the string. The zero-padded string will have this width.

Return Value

This method returns the zero-padded string.

Example

The following example demonstrates the use of the zfill() method.

var = "this is string example....wow!!!"
var1 = var.zfill(40)
print ("original string:", var)
print ("string padded with 0:", var1)

Running this program will produce the following output:

original string: this is string example....wow!!!
string padded with 0: 00000000this is string example....wow!!!

The following program uses

var="Hello python"
var1=var.center(40)
var2=var.ljust(40, '*')
var3=var.rjust(40, '*')
print ("original string: ", var)
print ("centered:", var1)
print ("left justified: ", var2)
print ("right justified:", var3)
var="HellotPython"
var4=var.expandtabs(16)
print ("capitalized:",var4)
var=-1234.50
var5=str(var).zfill(10)
print ("zfilled:",var5)

Running this program will produce the following output:

original string: Hello python
centered: Hello python
left justified: Hello python****************************
right justified: ****************************Hello python
capitalized: Hello Python
zfilled: -0001234.5

Instance methods related to alignment are also available as static methods of Python’s str class. The following program uses the equivalent static methods.

var="Hello python"

var1=str.center(var, 40)
var2=str.ljust(var, 40, '*')
var3=str.rjust(var, 40, '*')

print ("original string: ", var)
print ("centered:", var1)
print ("left justified: ", var2)
print ("right justified:", var3)

var="HellotPython"
var4=str.expandtabs(var, 16)
print ("capitalized:",var4)

var=-1234.50
var5=str.zfill(str(var), 10)
print ("zfilled:", var5)

Running this program will produce the following output:

original string: Hello python
centered: Hello python
left justified: Hello python****************************
right justified:****************************Hello python
capitalized: Hello Python
zfilled: -0001234.5

Leave a Reply

Your email address will not be published. Required fields are marked *