What is filter, map, and reduce in python and how to use them?
Filter, map, and reduce are three ways to handle sequences in Python. Typically, using a simple for-loop can achieve the same effects. But for a more elegant code, those built-in functions can be used.
Similar built-in functions can be found in other programming languages as well.
# here, the sequence can be list/string/tuple# takes a function and a sequence; returns filter object;
# function, sequence -> filter object
filter(function, sequence)# function, sequence -> map object
map(function, sequence)# function, sequenc -> reduce object
How to use regex in Python?
From part 1, we understand how to write some simple regular expressions. But how do we actually use it in Python? This post will focus on different ways of using it in Python.
To use regular expression in Python, a module called re needs to be imported.
There are a few different methods we can use in re module.
import re# re module function contractsre.match(regex_pattern, string_to_search)re.fullmatch(regex_pattern, string_to_search)re.search(regex_pattern, string_to_search)re.findall(regex_pattern, string_to_search)
Now let’s see some examples where we use those functions
Let’s say now we need to validate if a string is a 10-digit phone number in format ‘XXX-XXX-XXXX’, we can do the…
What is regular expression and how do we use it?
Regex stands for regular expression. It essentially uses a string pattern to search within strings.
The regular expression can be used for the following scenarios:
Since there is a lot to cover for regular expression, I will make two posts for regex. This post will focus on some simple regex, and the next post will focus on how to use it on python.
Let’s say now you made a form and users need to enter their 10-digit phone number in this format
XXXXXXXXXX (e.g 1231231234), how do you make sure users always enter a valid birthday using regular expression? Well, the first method we can do is check if the user enters 10 digits. Depending on the programming language you use, we can first check if all the characters entered are digits and if the length of that is 10. But we can do it in a more elegant way using a regular expression. …