Pages

Thursday, April 8, 2021

String method zfill() in Python

String Method - zfill()

While working with numeric values in a string format, it becomes essential to have the data for a specific length as required i.e., filling the leading blanks with zeros. 

E.g.: If we have number 470 and need to mention this in 5 digits in character format, two leading zeros to be added to make it 5 digits. 

470 --> 00470

String method 'zfill()' is very useful to achieve this. 

Syntax:

str.zfill(width)

Method zfill accepts one argument 'width' which defines the minimum number of digits (width) the return string should be. This method doesn't amend the original string. 

Before we see an example, Below are the few points to consider. 
  • zfill is a string method and cannot be directly used with int or float or other data types. 
  • Width passed as an argument is the minimum number of digits is by considering the period (.) and any prefix (+/-). 
  • If the original string has more width than the width passed in the argument, return string would be same as original string. 
  • No data validation would be done on the string. If the string contains alpha or alphanumeric characters, leading zeros would still be added based on the width passed. 
Let's have a look at few examples to understand this better. 

E.g.: 

Convert the number 470 to a string of 5 digits by appending leading zeros. 

String method zfill() in Python

In the above example, we are doing this in two different ways. 
  • First Method (Line - 2): We are directly mentioning 470 as a string and using the zfill method by passing the width '5' as an argument. This looks easy to understand how zfill works, but we may not be able to do this always and the data tend to change.
  • Second Method (Lines - 6 & 7): We are creating an integer variable by assigning the value 470. And, converting the integer to string by using str() function and using the zfill method on the result. 

The above example is straight forward there are no decimal values or prefixes. So, what would happen if we have decimal values and/or prefixes. 

String method zfill() in Python

In the above example, 
  • Lines - 1 & 2: We are using zfill on the number -470 (prefixed with -, total of 4 digits currently) and the result is '-0470' (only one leading zero is added). Width of the result string is by considering the prefix. 
  • Lines - 5 & 6: We are using zfill on the number -47.0 (prefixed with - and contains ., total of 5 digits currently) and the result is '-47.0' (no change). Current length of the number (converted to string) is same as the width passed, So no change would be done.
Let's have a look at another example where the input number is greater than the width passed. 

String method zfill() in Python

In the above example, both numbers are exceeding the width passed (5) and original string would be returned in this case. 

As mentioned above, No validation would be done on the input string. If alpha or alphanumeric data is passed, zfill would still return a string by appending leading zeros. 

String method zfill() in Python

In the above example, two leading zeros have been added to 'ABC' to return the string of length '5'. 

Hope the above info was useful in understanding the usage of method zfill(). 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Sunday, April 4, 2021

Usage of map() function in Python

Usage of map() function in Python - Explained

Python map() function is very helpful when we need to call a specific function for each element in an iterable and return the result as an iterable of type map object. 

In other words, map() function would call another function for each element in an iterable (range, list, tuple...) and returns an iterable.

Syntax

map(function, iterable1, iterable2,...)

map() accepts a minimum of two parameters.
  • A function (to be called)
  • An iterable (function to be executed for each element in an iterable)
And, can have multiple iterables as required by the function passed in the first parameter. If the function requires two parameters then two iterables to be passed in parameters for map function. 

Let's have a look at an example to calculate the square of each number in the range of 0 to 5.

Without using map()


map() function in Python

In the above example, 
  • Line - 3: Create empty list to hold square of numbers. 
  • Line - 6: for loop over range of 0 and 5. 
  • Line - 7: pass number to the function 'square' to get the square of the number and add it to the list created. 
  • Line - 13: Function 'square' to accept a number as parameter and return the square of the number as result. 
Here we are using for loop to call the function for each number in the range of 0 and 5. 

We can use map() function to do that instead of having for loop. 

With map() function


map() function in Python

In the above example, 
  • Line - 3: We are passing the function 'square' as first parameter and range(5) as second parameter to the map function and assigning the result to variable 'square_list'. 
Only difference here would be 'square_list' is an iterable of type map object not a list. Print statement above doesn't actually print squares instead it just prints '<map object at memory_location>'.

Values in the map object can either be accessed by using this in for loop or simply by converting the map object to list. 

square_list = list(map(square, range(5)))

Just like in the above example, if we are only creating the function to use it in map, we can avoid function creation by using lambda expression. 

map() with lambda expression


map() with lambda expression in Python

In the above example, 
  • Line - 3: We are using lambda expression to calculate the square of a number in the range 0 to 5 instead of having to create a function. 

map() with two or more iterables

We can pass multiple iterables to map function as required by the function passed. 

Let's have a look at an example with a function to add two numbers and return the result by passing two iterables. 

map function with multiple iterables

In the above example, 
  • Line - 14: Creating a function to accept two numbers and return the sum of two numbers.
  • Lines - 3 & 6: Creating two lists with numbers. Note that the number of elements in the two lists aren't same. 
  • Line - 9: passing the function and two lists to the map function. 
There are couple points to note regarding the way map function works when two or more iterables are passed. 
  • Elements in the same index position would be passed as parameters to the function. E.g.: Index 0 from first list & second list, Index 1 from first list & second list, Index 2 from first list & second list and so on.
  • If the number of elements in the lists aren't same, map function would return the results equal to the smallest index. In the above example second element has got only 3 elements and the result would contain the sum of first 3 elements from the two lists. 

map() function with Python BIF

Like user created functions, we can use Python Built-In Functions as well inside the map() function. 

We will have a look at converting the numbers in a string (or user input) to a list by converting them to int. 

map() with int in Python

In the above example, 
  • Line - 2: A string called 'numbers' with a string containing numbers. This can either be an user input (which is most common scenario) that is to be split into a list of numbers. 
  • Line - 5: We are passing function 'int' and an iterable (by splitting the string into a list using split method). 
Like any other function, int would convert each of the number from the iterable passed and returns the integer value. This is them stored as a map object and converted to list (by using list function). 


Hope the above info was useful in understanding the usage of map() function. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python Exception handling is key for any programming language. When an exception occurs Python interpreter stops execu...