Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

F-strings: Formatting Text Output

Recommended resources

Introduction

Welcome to your first lesson! The goal of this course is to build your foundational Python skills, focusing on practical applications that bridge the worlds of coding and writing. We'll move step-by-step towards projects that could be relevant for fields like data journalism or technical writing. This first module is all about working with text, a skill that is fundamental to both programming and journalism.

In this lesson, we'll tackle our first learning outcome: to declare string variables and format text output using f-strings. You'll learn how to store textual information in your programs and how to present that information in a clean, readable, and dynamic way. This is a crucial first step for everything from generating simple reports to creating complex, data-driven narratives.


What are Variables and Strings?

In programming, a variable is like a labeled container where you can store a piece of information. This allows you to refer to that information by a convenient name throughout your code.

When the information you want to store is text, it's called a string. In Python, you create a string by enclosing text in either single (') or double (") quotes. Let's declare a couple of variables: one to hold a name (a string) and another to hold an age (an integer).

author_name = "Jane Doe"
article_count = 54

Now, what if we want to print a sentence combining this information? In the past, this was often a bit clumsy. You might have to manually convert numbers to strings and "add" the pieces together with + signs. This process is not only tedious but also prone to errors, especially when mixing text and numbers.

Fortunately, modern Python offers a much more elegant and powerful solution: f-strings.


The Power of F-Strings

The 'f' in f-string stands for "formatted." It's a way to embed Python expressions, like your variables, directly inside a string. This makes your code dramatically easier to write and read.

To create an f-string, you simply prefix your string with the letter f or F. Then, you can place your variables directly inside curly braces {} within the string. Python will automatically replace the braces with the variable's value.

This image shows the three simple steps of using an f-string: define your variables, write the string with an 'f' prefix and placeholders, and let Python generate the final result.

To see this in action and understand why it's a significant improvement over older methods, let's watch a short video from Corey Schafer, a well-regarded Python educator.

Python Quick Tip: F-Strings - How to Use Them and Advanced String Formatting

This video provides a clear introduction to f-strings.

Watch the first three minutes, from the beginning to the explanation of how f-strings work with variables. Pay attention to how the f-string syntax directly places the variable names inside the string, making it much more intuitive than the older .format() method he shows for comparison.


As you saw, the syntax is clean and direct. Instead of managing placeholders and a separate list of variables, the context and the content live together.

You're not limited to simple variables, either. You can access data from more complex structures, like dictionaries, and even call functions right inside the braces.

Python Quick Tip: F-Strings - How to Use Them and Advanced String Formatting

The same video also demonstrates these more advanced capabilities.

First, watch the segment on using methods like .upper() inside an f-string. Then, watch the section on working with dictionaries. Note the important tip about using different types of quotation marks (e.g., double quotes for the string if you use single quotes inside the braces).



Advanced Formatting for Professional Output

Simply inserting values is useful, but the true power of f-strings lies in their formatting capabilities. You can control how numbers are displayed, align text in columns, and much more. This is essential when you need to create professional-looking reports or tables—a common task in data journalism.

F-strings allow for a wide range of formatting options, from controlling decimal places to formatting dates, all within the string itself.

The following article uses a creative story about a shop sign to explore these formatting features. It's a great example that will likely appeal to your creative writing background.

The Curious Little Shop at The End of My Street • Python's f-strings

This article provides a narrative-driven look at why formatting is important and how to achieve it with f-strings.

First, read the section The Old Way to see the problem f-strings solve. Next, read the introduction to f-strings, which reinforces what you saw in the video. Finally, focus on the section Introducing Format Specifiers. This introduces the colon : syntax used to format values, such as controlling the number of decimal places.

Let's break down the key formatting capabilities.

Formatting Numbers

When dealing with data, you often need to format numbers for readability.

  • Decimal Places: You can round a number to a specific number of decimal places using :.nf, where n is the number of decimal places. This is perfect for prices, percentages, or scientific measurements.
  • Thousand Separators: You can make large numbers easier to read by adding a comma as a thousand separator with :,.

The next video provides excellent visual explanations for these formatting options.

Python F-strings - Visually Explained

This video uses clear animations to demonstrate how formatting expressions work.

First, watch the segment on rounding decimals. Then, watch the part that explains how to add comma separators to large numbers.


Aligning Text

Creating tabular data—like a list of statistics or a price list—requires aligning text into columns. F-strings handle this with ease. You can specify a total width for your value and then align it to the left (<), right (>), or center (^).

The "Curious Little Shop" article provides a perfect, practical example of building a neatly formatted price list.

The Curious Little Shop at The End of My Street • Python's f-strings

This section walks through a complete example of creating a formatted table.

Read the section Back to the Shop. Pay close attention to how they combine width, alignment, and number formatting (:10,.2f) to create a clean, aligned price column. This is a powerful technique for data presentation.


Putting It All Together: A Mini-Report

Let's apply what you've learned to a task relevant to journalism. Imagine you have some raw data about an author and you want to generate a small, formatted profile card.




# Data for our subject
author_name = "Priya Singh"
age = 34
books_published = 12
total_sales = 2150478
average_rating = 4.8751




# Generate a formatted profile card using a multi-line f-string
profile_card = f"""
================================
AUTHOR PROFILE
--------------------------------
Name:    {author_name}
Age:     {age}
Works:   {books_published} published books
Sales:   ${total_sales:,.2f}
Rating:  {average_rating:.1f}/5.0
================================
"""

print(profile_card)

Try running this code yourself! Notice how we combine several techniques:

  • A multi-line string using triple quotes """ to structure the card.
  • The :, format specifier to make the total_sales figure readable. We also add .2f to show it as a monetary value.
  • The :.1f specifier to round the average_rating to one decimal place for a cleaner look.

This simple script demonstrates how a few lines of Python can transform raw data into a polished, human-readable output.


Conclusion

In this lesson, you've taken your first step into practical Python programming. We've seen how variables act as containers for data and how f-strings provide a powerful and readable way to format text.

Here are the key takeaways:

  • Variables store information, and strings are used for text.
  • F-strings, created by prefixing a string with f, let you embed variables and expressions directly within {}.
  • You can use format specifiers (like :.2f for two decimal places or :, for thousand separators) inside the braces to control the appearance of your output.
  • These tools are fundamental for creating clean, professional, and dynamic text, which is a core skill for any text-based programming application.

In our next lesson, we will continue to build your text-processing toolkit. We'll explore various string methods, such as .lower(), .split(), and .replace(), which allow you to clean, parse, and manipulate text data—an essential step before any analysis can begin.