This is the second in a collection of articles about options that first appeared in a model of Python three.x. Python three.1 was first launched in 2009, and regardless that it has been out for a very long time, most of the options it launched are underused and fairly cool. Here are three of them.
When formatting massive numbers, it is not uncommon to put commas each three digits to make the quantity extra readable (e.g., 1,048,576 is less complicated to learn than 1048576). Since Python three.1, this may be completed straight when utilizing string formatting features:
"2 to the 20th power is :,d".format(2**20)
'2 to the 20th energy is 1,048,576'
,d format specifier signifies that the quantity should be formatted with commas.
collections.Counter class, a part of the usual library module
collections, is a secret super-weapon in Python. It is commonly first encountered in easy options to interview questions in Python, however its worth isn’t restricted to that.
For instance, discover the 5 most typical letters within the first eight strains of Humpty Dumpty’s song:
hd_song = """
In winter, when the fields are white,
I sing this tune in your delight.
In Spring, when woods are getting inexperienced,
I will try to inform you what I imply.
In Summer, when the times are lengthy,
Perhaps you will perceive the tune.
In Autumn, when the leaves are brown,
Take pen and ink, and write it down.
collections.Counter(hd_song.decrease().change(' ', '')).most_common(5)
[('e', 29), ('n', 27), ('i', 18), ('t', 18), ('r', 15)]
Python permits the
-m flag to execute modules from the command line. Even some standard-library modules do one thing helpful once they’re executed; for instance,
python -m cgi is a CGI script that debugs the net server’s CGI configuration.
However, till Python three.1, it was inconceivable to execute packages like this. Starting with Python three.1,
python -m package deal will execute the
__main__ module within the package deal. This is an efficient place to place debug scripts or instructions which might be executed largely with instruments and don’t should be brief.
Python three.zero was launched over 11 years in the past, however a number of the options that first confirmed up on this launch are cool—and underused. Add them to your toolkit if you have not already.