Python String Formatting Tutorial – Complete Guide

Welcome to the exciting world of Python string formatting! In this comprehensive tutorial, you’re in for a ride into understanding and utilizing Python’s versatile feature of string formatting. It doesn’t matter whether you’re just starting your coding journey or are a seasoned programmer craving to add another notch to your coding tool belt – this guide will ensure a firm grasp of Python string formatting.

String Formatting – The ‘What’ and ‘Why’

So, what exactly is Python string formatting, you may ask? Simply put, it is a method in Python that allows us to control and manage how strings are represented.

Let’s put that into perspective with a gaming-related analogy. Consider a role-playing game with customizable characters. Just as you can modify a gaming avatar’s appearance, string formatting in Python lets you modify a string’s output according to your needs.

But why should you take the time to learn Python string formatting?

With string formatting, your code can become more efficient, readable, and versatile. Being able to format strings is akin to having a magic key: it opens up a plethora of possibilities, making your code more adaptable and dynamic — much like a character in a game who can adapt to any challenges thrown their way!

Now that we’ve established what Python string formatting is and why it’s important, let’s get to the practical part! We are going to learn by doing, just like how you would jump straight into playing a new game to get the hang of it.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Old Style String Formatting (%)

First, let’s look at the conventional “old style” of string formatting that uses the “%” operator. This technique is analogous to the sprintf() style used in C programming.

# Strings are represented with '%s'
name = "Alice"
print("Hello, %s!" % name)

This code will output: Hello, Alice! Fantastic! You’ve just formatted your first string.

Similarly, you can use ‘%d’ for decimal integers, and ‘%f’ for floating-point numbers.

points = 20
print("You have earned %d points!" % points)

pi = 3.14
print("Value of pi is %f" % pi)

The output will be: You have earned 20 points! Value of pi is 3.140000

String Formatting with the str.format() method

Another popular method is the str.format(). It’s newer and much more powerful. It’s akin to achieving higher levels in a game, enabling more abilities and weapons.

print("Hello, {}! You have {} points".format(name, points))

The output will be: Hello, Alice! You have 20 points. Note how the arguments in the format() method get substituted into the string in the order they are provided.

Now, let’s learn about positional and keyword arguments to customize our strings further. Positional arguments refer to the order of parameters and keyword arguments are identified by the parameter names.

print("{1}, {0}, and {2}".format('A', 'B', 'C'))

print("{name} loves playing {game}".format(name="Charlie", game="Chess"))

The output will be: B, A, and C \n Charlie loves playing Chess

Formatted String Literals (f-strings)

Introduced in Python 3.6, f-strings (also known as formatted string literals) have quickly become a favorite amongst Python programmers. Think of f-strings as your secret cheat code – they’re fast, easy, and efficient – and they help you level up your string formatting game!

print(f"Hello, {name}! It's nice to meet you.")

This will output: Hello, Alice! It’s nice to meet you. You can include variables or expressions directly within the curly braces of your string.

As you can see, learning Python string formatting is like practicing a new game technique. With every technique learned and mastered, your coding skills level up!

Number formatting with f-strings

f-strings aren’t just for inserting variables and expressions into strings. They also allow us to format numbers in our strings. This ability is like finding hidden Easter eggs in a game – exciting and useful!

score = 3.14159
print(f"Pi rounded to two decimal places is {score:.2f}")

This will output: Pi rounded to two decimal places is 3.14

Dynamic Expressions with f-strings

What makes f-strings really stand out is that you can include dynamic Python expressions within your strings, not just static values. This is like a chameleon in a game who can dynamically adapt to different environments!

a = 5
b = 10
print(f"The sum of {a} and {b} is {a+b}.")

This will output: The sum of 5 and 10 is 15.

f-string and Dictionaries

One of the most powerful features of Python is its ability to work with various types of data. The f-string formatting works seamlessly with arrays, dictionaries and more! This diversity is like having a multi-tool gadget in a game.

player_scores = {"Bob": 7, "Alice": 9}
print(f"Bob scored {player_scores['Bob']} points, Alice scored {player_scores['Alice']} points.")

This will output: Bob scored 7 points, Alice scored 9 points.

String Formatting and Time

One special edge case where string formatting comes in handy is when working with datetime objects. It can handle the peculiarities of such objects, much like a time-travelling power in a game!

import datetime
now = datetime.datetime.now()
print(f"The current date and time is: {now:%Y-%m-%d %H:%M}")

This will output something like: The current date and time is: 2022-02-02 15:35.

So there you have it! Python string formatting may seem a bit complex at first, like getting used to a new game, but the more you practice, the better you get. The rewards you reap with well-constructed and clear code are definitely worth the effort!

Where to go next

You now have a solid understanding of Python string formatting, but don’t stop here! The world of Python is vast and ever-expanding, just like the immersive open worlds in video games. You’ve got the skills – now it’s time to continue your journey of coding victory.

We highly recommend checking out the comprehensive Python Mini-Degree offered by us at Zenva Academy. The Python Mini-Degree puts you right in the driver’s seat of learning, offering you hands-on projects such as building your own games, developing apps, and even crafting AI chatbots. Python is currently the world’s most preferred programming language and is in high demand in the job market, particularly in the field of data science.

The courses are suitable for both beginners and experienced programmers, offering flexible learning options with the ability to jump straight to relevant lessons. The curriculum is specifically crafted to provide you with real-world skills that can help you change careers, land your dream job, or even start your own business.

Plus, with classes led by qualified instructors, interactive lessons, and coding challenges, you’ll be able to earn completion certificates and build a professional portfolio.

Ready to explore Python more broadly? Dive into our extensive collection of Python courses.

Conclusion

By reaching the end of this tutorial, you’ve made significant strides in your Python journey! Just as in gaming, every technique learned and every skill mastered brings you closer to being a Python connoisseur. Python string formatting, much like conquering a challenging game level, is no longer a mystery to you.

It’s time to capitalize on the momentum! With Zenva, you can explore further, conquer more complex concepts, and level up your Python skills. Our Python Mini-Degree is a treasure trove of comprehensive lessons, ready to unlock uncharted territories in your Python knowledge. As you continue to invest in your coding education, remember that every challenge tackled is another victory notch on your coding tool belt. So let’s keep achieving together!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.