Advertisement



< Prev
Next >



Python - String zfill() Method



The zfill() string method is used to strech the length of an invoked string by filling it with a number of zeroes at its beginning.

If the original length of an invoked string is already greater than its length that we want to achieve by adding zeroes to it, then no zeroes are added at the beginning of such invoked string.

Note : None of the string methods change the original string and they only return a new string which reflects the change performed by the string method, hence the returned string must be stored or used(if needed to reflect the result), otherwise it is lost.




If the original length of an invoked string is already greater than its length that we want to achieve by adding zeroes to it, then no zeroes are added at its beginning. Let us see an example.

# Python - zfill() method example.



# Creating a string
s = 'Eat healthy, live healthy!'


# Printing the original string
print('Original string is : ', s)



# Finding the length of string by calling len() method
print('length of string : ', len(s))


# Calling  the zfill() method on string object
# by passing its parameter length a value of 10
# which is already less than the length of the invoked string i.e. 26
# Hence, no filling will be made.
print(s.zfill(10))



# Calling  the zfill() method on string object
# by passing its parameter length a value of 20
# which is already less than the length of the invoked string i.e 26
# Hence, no filling will be made.
print(s.zfill(20))




# Calling  the zfill() method on string object
# by passing its parameter length a value of 20
# which is one length greater than the length of the invoked string i.e 26
# Hence, one zero will be added at the beginning of the string' content.
print(s.zfill(27))


Output is :


Original string is :  Eat healthy, live healthy!
length of string :  26
Eat healthy, live healthy!
Eat healthy, live healthy!
0Eat healthy, live healthy!





Please share this article -





< Prev
Next >
< String rpartition() Method
Python - String Formatting >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement