Search⌘ K
AI Features

Composing Functions

Explore how to compose two functions in Python to create new function objects. Learn to use a generic compose function with examples, understand its advantages over procedural code, and apply it with tools like map to process strings and create anonymous functions.

Example: Convert a character into a hex string

Let’s suppose you needed a function that could convert any character; for example, “a” can be converted into a hex string representing its ASCII character code (“0x61”).

There are two functions in Python that you can use to do this. ord converts a character to an int value representing its ASCII code (or more generally its Unicode value). hex converts an int value into a hex string. Using these two functions, we can define a function that does the task for us, as shown below.

Python 3.8
def codestr(c):
return(hex(ord(c)))
h = codestr('a')
print(h) # '0x61'

In this code, we apply the ord function to value c and then apply the hex function to the result.

Applying one function ...