Rezha Julio

The Hard Coded Chemist

Your Own Python Calendar

The Python calendar module defines the Calendar class. This is used for various date calculations as well as TextCalendar and HTMLCalendar classes with their local subclasses, used for rendering pre formatted output. Import the module: import calendar Print the current month: import calendar year = 2016 month = 1 cal = calendar.month(year, month) print(cal) The output will look like this: January 2016 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Set the first day of the week as Sunday: Continue reading

Get the Most of Floats

Similar to the int data type, floats also have several additional methods useful in various scenarios. For example, you can directly check if the float number is actually an integer with is_integer(): >>> (5.9).is_integer() False >>> (-9.0).is_integer() True Integer values might be preferred over floats in some cases and you can convert a float to a tuple matching a fraction with integer values: >>> (-5.5).as_integer_ratio() (-11,2) # -11 / 2 == -5. Continue reading

Format text paragraphs with textwrap

Python’s textwrap module is useful for rearranging text, e.g. wrapping and filling lines. Import the module: import textwrap Wrap the text in the string “parallel”, so that all lines are a maximum of x characters long: # When x = 2 textwrap.wrap("parallel", width=2) # Output: # ['pa', 'ra', 'll', 'el'] # When x = 4 textwrap.wrap("parallel", width=4) # Output: # ['para', 'llel'] Returns a list of lines (without trailing newlines). Continue reading

Unicode Character Database at Your Hand

Python’s self explanatory module called unicodedata provides the user with access to the Unicode Character Database and implicitly every character’s properties. Lookup a character by name with lookup: >>> import unicodedata >>> unicodedata.lookup('RIGHT SQUARE BRACKET') ']' >>> three_wise_monkeys = ["SEE-NO-EVIL MONKEY", "HEAR-NO-EVIL MONKEY", "SPEAK-NO-EVIL MONKEY"] >>> ''.join(map(unicodedata.lookup, three_wise_monkeys)) '🙈🙉🙊' Get a character’s name with name: >>>'~') 'TILDE' Get the category of a character: >>> unicodedata.category(u'X') 'Lu' # L = letter, u = uppercase Also, using the unicodedata Python module, it’s easy to normalize any unicode data strings (remove accents, etc): Continue reading

Functional Particularities of Python

This time we’ll explore some of the paradigms of functional programming as applied to Python, specifically. One of the most common constructs to employ in a functional-style Python program is a Generator. Generators are a special class of functions that make writing iterators [1] more easy. When we call a function, a new space in memory is allocated to hold all of the variables that function is concerned with, as well as other data. Continue reading
Older posts