Introduction:

In this lesson, we’ll learn two essential concepts in Python: string formatting and string slicing. These tools allow you to manipulate and display text in a neat and organised way, making your programs more dynamic and user-friendly.

String Formatting:

String formatting is useful when you want to insert variables or values into a string. We’ll focus on two popular methods:

  1. .format(): This method lets you insert variables into placeholders {} within a string.
  2. f-strings: A more modern and convenient way to format strings, allowing you to embed variables directly into a string by prefixing the string with an f.

String Slicing:

Slicing allows you to extract specific parts of a string, like grabbing the first few letters of a name or cutting out a segment of text. You can slice using the syntax myString[start:end].

Real-World Example:

Imagine you’re creating a report that needs to display names and scores neatly, or you want to display the initials of a user. Formatting helps organise the data, while slicing helps extract specific parts of the strings.

Let’s see some examples of both formatting and slicing:

Predict:

Can you predict the output of this code? We are using an f-string for formatting and slicing to extract initials.

first_name = "Christopher"
last_name = "Nolan"
# Formatting with f-string
message = f"Director: {first_name} {last_name}"
print(message)
# Slicing to get initials initials = first_name[0] + last_name[0]
print(initials) 

Think about how the f-string works and how the slicing extracts the first letters of the names.

Run:

Let’s practice Python string formatting and slicing together. Run the following code to see both methods in action.

This example:

  • Inserts the name and age into a sentence using .format().
  • Slices out the first word ("Learning") from the string "Learning Python".

Investigate:

Now, let’s explore how f-strings work along with string slicing. Run the following code and observe how formatting and slicing are combined to manipulate the string.

Instructions:

  • Notice how f-strings make it easy to insert variables into a string directly.
  • Investigate how slicing works when using negative indices (-6 means extracting the last 6 characters of the string).

Modify:

The following code attempts to slice the string but has a mistake in how it extracts the first part of the name. Can you fix it?

Hint: Check the slice indices. The correct way to slice out the first 4 letters should be name[:4].

Scroll to Top