Composing Functions

Learn how to compose functions in a functional way in this lesson.

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.

Press + to interact
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. ...