![]() What is new in the previous statement? Well. Let me add the next statement before to have the final script ![]() Returning to the above statement about why a compiled regex object, one of the best answers is because we can reuse the compiled expression and even have the possibility of using the regex sub function, having in one simple line the power to combining lambda function, regex sub and dictionary for getting the desired result. This function returns a new string as an outcome from performing replacements on a search string, for more information visit this link: Īs the documentation mentioned, inside of regex sub function we can specify as a function and therefore the regex sub will call this function for each match found, so instead of passing a function, is here where we can use the regex sub together with a lambda expression and I think that this kind of scenario represents a good opportunity to implement a lambda expression. Maybe you are asking why was required to have a compiled regex object, but before start to explain to you the main reason, I want to introduce you to a part of the regular expression and which we will be using, it is regex.sub, here the syntax: Let me show you the following piece of code where we cover the new dictionary and creation of compiled regex object: Once that we have completed, we are going to compile a regex for use later, the regex will be composed of all the keys which are coming from the formatted dictionary and split them with the symbol “|”, explaining the benefit of compile a regex is out of the scope of this post, but you can find interesting articles about it. In this case, we will be building a new dictionary comprehension and applying the regular expression escape function to backslash it. The first step will consist of yielding a new dictionary that we will backslash the special symbols in the dictionary’s key to avoid conflicts related to special symbols, this is because Python strings also use the backslash to escape characters. ![]() The regular expression(shortened as regex or regexp) also allows us to define a search pattern, that is vital for our use case explained above. “ A regular expression (or RE) specifies a set of strings that matches it ”. We need to start with a short explanation of regular expression, it does not belong only to the Python world, in fact, we can found it in many modern language programming, nonetheless, I want to cite the Python documentation for his definition: As you can see the values contained in the dictionary match with words of the request variable, but in common scenarios, the dictionary is not limited to a few keys, so the approach addressed in this article focus on bringing you outcomes accurately even when we have to deal with hundreds of items.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |