📜 ⬆️ ⬇️

Analogs in Python and JavaScript. Part two

We continue to publish a translation of a series of articles on the similarity and difference of two languages.


Today we will talk about serialization of dictionaries, JSON, regulars, errors and exceptions.


Other articles in this series:


  1. The first part is type conversion, ternary operator, property access by property name, dictionaries, lists, strings, string concatenation.
  2. This article
  3. Part three : modern Python and JS: string patterns (f-strings), list unpacking, lambda functions, list iterations, generators, sets.
  4. The fourth part is the function arguments, creating and working with classes, inheritance, setter getters, and class properties.

Json


When working with many APIs, it is convenient to serialize objects into JSON objects for ease of transfer and subsequent parsing.


In Python, there is a standard json module:


import json json_data = json.dumps(dictionary, indent=4) dictionary = json.loads(json_data) 

Here we format JSON with 4 spaces.


In JS, there is a JSON object with methods for creating and parsing JSON strings:


 json_data = JSON.stringify(dictionary, null, 4); dictionary = JSON.parse(json_data); 

Parse strings


In the last article, we connected several lines into one. But how to divide one long line into several, especially if the separator is not one character like a comma, but a whole range of different options? This is where regular expressions and the split() method come to our aid.


In Python, the split() method refers to a regular expression pattern. Here's how to split a text string into sentences by punctuation:


 import re #     "!?."         delimiter = re.compile(r'[!?\.]+\s*') text = "Hello!!! What's new? Follow me." sentences = delimiter.split(text) # sentences == ['Hello', "What's new", 'Follow me', ''] 

In JS, the split() method refers to strings:


 //     "!?."         delimiter = /[!?\.]+\s*/; text = "Hello!!! What's new? Follow me."; sentences = text.split(delimiter) // sentences === ["Hello", "What's new", "Follow me", ""] 

Regular search in a pattern


Regular expressions are often used to validate form data.
For example, to verify the correctness of the entered e-mail address, it must be compared with a regular expression pattern.


Written translation in the course

that address checking by regulars is a nontrivial task and is somewhat more complicated than the method given in this article


In Python, it will look something like this:


 import re # name, "@", and domain pattern = re.compile(r'([\w.+\-]+)@([\w\-]+\.[\w\-.]+)') match = pattern.match('hi@example.com') # match.group(0) == 'hi@example.com' # match.group(1) == 'hi' # match.group(2) == 'example.com' 

If a section of text coincides with a template, then using the group() method, the matched section is returned in which you can select individual groups defined in the template.


0 - the entire matched (sub) string, 1 - the first group, 2 - the second, etc.


If no match is found, a None object will be returned.


In JS, there is a string method match() which returns either the matched portion of the string or null .


 // name, "@", and domain pattern = /([\w.+\-]+)@([\w\-]+\.[\w\-.]+)/; match = 'hi@example.com'.match(pattern); // match[0] === 'hi@example.com' // match[1] === 'hi' // match[2] === 'example.com' 

In JS, the matched object looks like an array. The element with the index [0] is the entire matched (sub) string, the 1st element is the first group, the 2nd is the second, and so on. - all in accordance with the groups defined in the template.


Sometimes, besides searching, it is required to determine the position of the sample in the text. This can be done using the search() method.
In Python, this method refers to regular expressions and returns the matched object. This matched object has a start() method that returns the beginning of the occurrence of this substring in the main string:


 text = 'Say hi at hi@example.com' first_match = pattern.search(text) if first_match: start = first_match.start() # start == 10 

In JS, there is a string search() method that returns the index of the start of a substring. Or -1 if no match was found.


 text = 'Say hi at hi@example.com'; first_match = text.search(pattern); if (first_match > -1) { start = first_match; // start === 10 } 

Pattern Replacement with Regular Expressions


Typically, pattern replacement is needed when you need to clear the data or add some properties to the text. For example, we can take a line and make all meeting email-addresses links:


In Python, there is a sub() regular expression pattern method for this:


 html = pattern.sub( r'<a href="mailto:\g<0>">\g<0></a>', 'Say hi at hi@example.com', ) # html == 'Say hi at <a href="mailto:hi@example.com">hi@example.com</a>' 

JS developers can use the string replace() method:


 html = 'Say hi at hi@example.com'.replace( pattern, '<a href="mailto:$&">$&</a>', ); // html === 'Say hi at <a href="mailto:hi@example.com">hi@example.com</a>' 

In Python, matched groups are available as \g<0>, \g<1>, \g<2> , etc.
In JS, similarly to $&, $1, $2 , etc.


It is also possible to replace the matched area with a function. Such functions are useful when replacing wrapping the source text or for counting, collecting or obtaining other information about the text. For example, when using a function call when replacing, you can write the syntax highlighting of HTML.


Let's change all meeting e-mail addresses with CAPITAL LETTERS.


In Python, the replace function gets the matched object. We use the group () method to perform actions with the matched text and return it as a replacement:


 text = pattern.sub( lambda match: match.group(0).upper(), 'Say hi at hi@example.com', ) # text == 'Say hi at HI@EXAMPLE.COM' 

In JS, the replace function gets the entire matched string, the first occurrence, the second, and so on. We perform the necessary actions and return the modified string:


 text = 'Say hi at hi@example.com'.replace( pattern, function(match, p1, p2) { return match.toUpperCase(); } ); // text === 'Say hi at HI@EXAMPLE.COM' 

Error processing


In contrast to Python, front-end browser-based JavaScript is usually not used for writing-reading files or accessing databases. Therefore, try..catch blocks try..catch quite rare in JS compared to try..except blocks in Python.


But, in any case, error handling can be performed in a user script, called from a library function, and intercepted in the main code.


In the following example on MyException , we define our exception MyException , MyException it in a function, and see how to catch and handle it in a try..except..finally block:


 class MyException(Exception): def __init__(self, message): self.message = message def __str__(self): return self.message def proceed(): raise MyException('Error happened!') try: proceed() except MyException as err: print('Sorry! {}'.format(err)) finally: print('Finishing') 

The following JS code does the same thing - we define the class MyException , MyException it in a function, intercept it, and process it in a try..catch..finally block:


 function MyException(message) { this.message = message; this.toString = function() { return this.message; } } function proceed() { throw new MyException('Error happened!'); } try { proceed(); } catch (err) { if (err instanceof MyException) { console.log('Sorry! ' + err); } } finally { console.log('Finishing'); } 

In both languages, the MyException class has a message parameter and a method for string representation depending on the value of message .


Of course, exceptions should be raised / raised only in case of an error. And if you identified this error in your module.


findings



As was said last time, you can line by line compare examples of the code given here in order to understand similar data structures and methods of working with them: strings, arrays, dictionaries, access to objects.


In the next part, let's talk about text patterns, unpacking lists, lambda functions, iterations without using indexes, generators, and sets.


')

Source: https://habr.com/ru/post/417513/


All Articles