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 a type conversion, a ternary operator, access to a property 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, setters 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.


There is a standard json module in Python:


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 method come to the rescue split().


In Python, the method split()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 the JS method split()refers to the lines:


// Один или более символов "!?." за которыми следует ноль или более пробельных символов
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 the template, then using the method group()returns the matched section entirely in which you can select the 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 type object will be returned None.


In JS, there is a string method match()that returns either the matched portion of the string either 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 method search().
In Python, this method refers to regular expressions and returns the matched object. This matched object has a method start()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 method that search()returns the index of the beginning of a substring. Or -1if 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 regular expression pattern method for this sub():



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 method replace():


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>and.
JS is similar $&, $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, blocks are try..catchquite rare in JS compared to blocks try..exceptin 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 Pione, we define our exception MyException, generate it in a function, and see how it is intercepted and processed in a block try..except..finally:


classMyException(Exception):def__init__(self, message):
        self.message = message
    def__str__(self):return self.message
defproceed():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 a class MyException, generate it in a function, intercept it, and process it in a block try..catch..finally:


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

In both languages, the class MyExceptionhas a parameter messageand method for string representation depending on the value message.


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


findings


  • Serialization to / from JSON is quite straightforward - as in Python that in JS.
  • Regulars is a powerful word processing tool in both languages.
  • Replacements can be made using functions.
  • For more complex cases, you can use call, intercept and error handling.

As it 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.


Also popular now: