Free Python course. Sign Up for tracking progress →

Python: The call chain

In this lesson, we'll look at how to combine different approaches when writing code, and we'll also look at common beginner mistakes.

We have the following code:

name = 'Tirion'
print(name.upper().lower())  # => `tirion`

He typed `tirion' on the screen.

This is the first time we have seen the syntax of several consecutive dots, but all the operations we encounter here are familiar. This code combines known features of the language.

This happens a lot in programming. If you don't know the syntax, you can still try combining different approaches, and chances are they will work.

To understand how this code works, you need to break down the chain into separate operations:

name = 'Tirion'
upper_name = name.upper()  # 'TIRION'
print(upper_name.lower())  # 'tirion'

The first and second examples are equivalent. We can perform operations sequentially with intermediate creation of variables, or we can build a continuous chain of attributes and methods. In chains, calculations always go from left to right.

One more example to reinforce:

name = 'Tirion'
print(name.replace('Ti', 'Ki').lower())  # => ?

This code needs a lot of thought. .lower() applies to the result of the method call, which is on the left. And the replace() method returns a string. Newbies often make mistakes in method chains and forget to place a call:

name = 'Tirion'
# This code will not work correctly!
print(name.upper.lower())

It is also possible to build infinitely long and useless chains that include slices:

# What is the result of such a call?
print(name[1:5].upper().find('I'))

This will not work with functions, since they are usually nested inside each other - f(f(f()))). This makes the analysis much worse. But that doesn't mean it can't be done nicely. In other languages, this is implemented through a composition of functions or a pipelining operator.

Instructions

Use the string cutter to get part of the sentence written in the text variable, from 5 to 15 characters inclusive. Process the resulting substring using the .strip() method and display the length of the resulting substring. Perform these operations in a chain without creating intermediate variables.