Home/Blog/Programming/Format strings in Python 3: A quick guide
Home/Blog/Programming/Format strings in Python 3: A quick guide

Format strings in Python 3: A quick guide

Maham Amjad
Nov 13, 2024
8 min read

Tim Berners-Lee, the inventor of the World Wide Web, said, “Data is a precious thing and will last longer than the systems themselves.” In modern software systems, data is often represented as strings. They represent textual information in different contexts, such as user inputs, database records, URLs, files, paths, and etc.

Key takeaways:

  • Formatting strings makes your code cleaner and easier to read, helping you present data in a clear and user-friendly way.

  • Python offers different string formatting techniques: the older % operator, the str.format() method, and modern f-strings. Each has its strengths and use cases.

  • Introduced in Python 3.6, f-strings simplify string formatting by allowing direct embedding of variables and expressions, improving readability and reducing verbosity.

Why is string formatting important?#

As a programmer, you often need to structure strings into a specific format to make them more readable and meaningful for users or systems. A few benefits of formatting strings are as follows:

  • It allows variable(s) and expression(s) to be embedded directly within the string.

  • It improves code readability by allowing developers to easily format data like numbers, dates, and text without complex concatenation.

  • It simplifies tasks such as debugging, creating user-friendly outputs, or displaying dynamic application content.

String formatting with Python:
Python 3 improves string formatting by introducing f-strings, specifically in Python 3.6. It allows developers to seamlessly embed variables and expressions into strings. Before Python 3, developers primarily used the % operator or the str.format() method, both of which had limitations.

If you’re new to Python and want to learn more about it, check out this comprehensive Python course.

Learn Intermediate Python 3

Cover
Learn Intermediate Python 3

Python is an important programming language used in data science, machine learning, web scraping, and web application development, making it essential for modern developers. This course starts with teaching fundamental programming concepts in Python 3, including conditional execution, repetition, and functions, before moving on to advanced topics like data structures and object-oriented programming. Quizzes and hands-on coding challenges along the way help reinforce what you have learned. By the end of this course, you will have a solid foundation in Python programming, enabling you to write clean and efficient code and tackle more advanced topics and projects with confidence.

10hrs
Beginner
254 Playgrounds
26 Quizzes

String formatting in Python 2.x#

Before Python 3, there were two main legacy methods for formatting strings:

  1. The % operator

  2. The str.format() method

Method 1: The % operator#

The % operator was the primary method for the old-style string formatting. This approach, reminiscent of C-style formatting, used placeholder symbols within a string:

name = "Python"
version= 3.12
print("Language: %s, Version: %.2f" %(name, version))

The "Language: %s, Version: %.2f" string (at line 4) contains two placeholders: %s (for a string) and %.2f (for a decimal number up to 2 decimal places). The % operator replaces the placeholders with the values as:

  • %s is replaced by the value of name.

  • %.2f is replaced by the value of version.

It is familiar to those with experience in C or similar languages but is less readable, especially for complex formatting needs.

Format Specifier

Description

%d

Used for signed decimal integers.

%i

Used for signed decimal integers, even if passed in as strings.

%s

Used for strings.

%f

Used for floating-point numbers (default precision 6).

%e

Used for scientific notation (lowercase e).

%E

Used for scientific notation (uppercase e).

%c

Used for single-character.

%%

Used for literal % character.

Method 2: The str.format() method#

Python 2.6 introduced the str.format() method. See the code below.

name = "Python"
version= 3.12
print("Language: {}, Version: {}".format(name, version))

The "Language: {}, Version: {}".format(name, version) string (at line 4) contains two placeholders: {}. The format() method replaces them with the values as follows:

  • The first {} is replaced by the value of name.

  • The second {} is replaced by the value of version.

It provides more control and flexibility over string formatting than the % operator. Look at the code below.

name = "Python"
version= 3.12
print("Language: {0}, Version: {1}".format(name, version))
print("Version: {1}, Language: {0}, Language again: {0},".format(name, version))
print("Language: {:>10}, Version: {:<5}".format(name, version))
  • Positional arguments: You can specify the position of the arguments in the placeholders {}. Line 4 formats the strings as follows:

    • {0}: It refers to the first argument passed to the format() function.

    • {1}: It refers to the second argument passed to the format() function.

  • Reordering or reusing arguments: You can reorder or reuse the arguments multiple times in the format string. Line 5 formats the strings as follows:

    • Version: {1}: It first inserts the second argument passed to the format() function.

    • Language: {0}: In second place, it inserts the first argument passed to the format() function.

    • Language again: {0}: It again inserts the first argument {0} in the end.

  • Padding: You can add padding to align values. Line 6 formats the string as follows:

    • {:>10}: It right-aligned the first argument within a field that is 10 characters wide. Any extra space will be filled with spaces on the left.

    • {:<5}: It left-aligned the second argument within a field that is 5 characters wide. Any extra space will be filled with spaces on the right.

With the str.format() method, strings are more readable and flexible than the % operator but are more verbose and less intuitive than Python 3’s f-strings.

Method 3: Formatting with Python 3’s f-strings#

Python 3 improves string formatting by introducing f-strings, specifically in Python 3.6.

With Python f-strings, the syntax is simpler, as the variables and expressions are directly placed within the string without needing separate arguments or a method call. Look at the code below.

name = "Python"
version= 3.12
print(f"Language: {name}, Version: {version}")
print(f"Version: {version}, Language: {name}, Language again: {name}")
print(f"Language: {name:>10}, Version: {version:<5}")
  • Less verbose: With Python f-strings, you can directly place the variable inside the placeholder. At line 4, the f-string f"Language: {name}, Version: {version}" does the formatting as follows:

    • {name} is replaced by the value of name.

    • {version} is replaced by the value of version.

  • No need for explicit indexing: With f-strings, you can refer to the variables wherever needed. There’s no need to keep track of indexes or formatting rules. Line 5 formats the string as follows:

    • Version: {version}: At first, it inserts the version.

    • Language: {name}: In the second place, it inserts the name.

    • Language again: {name}: It again inserts the name at the end.

  • Padding: You can add padding to align values. Line 6 formats the string as follows:

    • {name:>10}: It right-aligned name within a field that is 10 characters wide. Any extra space will be filled with spaces on the left.

    • {version:<5}: It left-aligned version within a field that is 5 characters wide. Any extra space will be filled with spaces on the right.

Evaluating expressions with Python f-strings#

With f-strings, we can add any valid Python expression inside {}, e.g., arithmetic operations, conditional statements, and function calls. Look at the code below.

def sum(x, y):
return (x + y)
x = 5
y = 10
print(f"The sum of {x} and {y} is {x + y}")
print(f"{x if x > y else y} is greater than {x if x < y else y}")
print(f'The sum of {x} and {y} is {sum(x, y)}')
  • Arithmetic operation: At line 7, the f-string replaces {x} and {y} with the values of previously declared variables: x and y (at lines 4–5). Whereas, {x + y} is an expression that evaluates the sum of x and y variables.

  • Conditional statement: At line 8, the f-string dynamically computes the comparison between x and y variables inside a string.

  • Function call: At line 9, the f-string computes the sum of x and y by calling the previously declared sum(x, y) function (at lines 1–2).

Formatting numbers with f-strings#

f-strings support various number formatting options, e.g., specifying decimal places, adding commas to large numbers, formatting percentages, and type conversion. Look at the code below.

number = 123456.789910
print(f"Rounded to 3 decimal places: {number:.3f}")
print(f"Formatted with commas: {number:,}")
percentage = 0.98765
print(f"Percentage format: {percentage:.2%}")
print(f"Binary: {10:b}, Hex: {10:x}, Octal: {10:o}")
  • Rounded to decimal places: At line 2, the format specifier, {number:.3f}, formats the number as a floating point number to three decimal places.

  • Number with commas: At line 3, the format specifier, {number:,}, tells Python to insert commas as thousand separators to make number more readable.

  • Percentage formatting: At line 6, the format specifier, {percentage:.2%}, formats the decimal percentage as a percentage, rounded to 2 decimal places.

  • Type conversion: You can convert expressions (values or variables) to different data types. Line 8 formats 10 in three different number systems as follows:

    • {10:b}: It formats 10 as a binary number (base 2).

    • {10:x}: It formats 10 as a hexadecimal number (base 16).

    • {10:o}: It formats 10 as an octal number (base 8).

Debugging with f-strings#

In Python 3.8+, f-strings introduce a debugging feature where = can be added after the expression to print both the expression and its result.

x = 42
print(f"x={x}")
print(f"{x=}")

Here, line 2 uses an f-string to print the value of x along with some custom text. Whereas, line 3 uses the debugging feature to automatically print the variable name and its value because Python interprets this as “print both the expression and its result.”

Handling dictionaries and objects with f-strings#

You can easily access dictionary values or object attributes inside an f-string. Look at the code below.

language = {'name': 'Python', 'version': 3.12}
print(f"Language: {language['name']}, Version: {language['version']}")
class Language:
def __init__(self, name, version):
self.name = name
self.version = version
langObj=Language('Python', 3.12)
print(f"Language: {langObj.name}, Version: {langObj.version}")
  • Dictionary access: At line 2, the dictionary language is accessed using its keys as follows:

    • {language['name']} retrieves the value associated with the key 'name'.

    • {language['version']} retrieves the value associated with the key 'version'.

  • Object access: The Language class is defined in lines 4–7, and its object is created in line 9. At line 10, the object langObj is accessed using its attributes as follows:

    • {langObj.name} retrieves the value associated with the attribute 'name'.

    • {langObj.version} retrieves the value associated with the attribute 'version'.

Conclusion#

The table below summarizes the information above to help you make an informed choice depending on your requirements and the Python version.

Method

Pros

Cons

The % operator

Familiar to those with C experience, simple for small tasks

Not very readable or flexible, can be hard to maintain with complex formats

The str.format() method

More control and flexibility with positional and named arguments

Verbose, requires keeping track of indexes/arguments

f-strings

Has simple syntax, allows direct embedding of expressions, and better readability

Requires Python 3.6+, fewer features in older versions of Python

You can make your code more efficient, readable, and maintainable by mastering different formatting techniques. Whichever method you choose will depend on your specific use case, but f-strings are highly recommended for modern Python applications.


In case, you want to deep dive in Python, check out the following path that will guide you from writing your first line of Python code to landing your first job as a Python developer. 

Become a Python Developer

Cover
Become a Python Developer

Launch your developer career by mastering the skills needed to become a Python programmer. Our structured lessons will guide you from writing your first line of code to landing your first job as a Python developer. With our interactive content, you’ll learn to code and explore Python beginner projects, tackle Python coding interview questions, and understand key topics such as OOP in Python, data structures in Python, and popular Python libraries. Whether you’re looking for Python programming examples or preparing for Python interview questions, this module offers everything you need to confidently enter the tech industry.

105hrs
Beginner
58 Challenges
55 Quizzes

Frequently Asked Questions

What is a conversion specifier in Python?

In Python, a conversion specifier is a placeholder used within a string to indicate how values should be formatted when using old-style string formatting with the % operator. It starts with the % symbol and is followed by a specific character or sequence that determines the type and format of the inserted value, such as %s, %d, %f, and %e.

How can we format the date with f-string in Python?

How can we escape curly braces in f-strings?

Do f-strings support multi-line strings?

Can we nest an f-string within another f-string?


  

Free Resources