String formatting in Python

0
(0)

String formatting is a key skill in Python, helping us manage output in a convenient and readable manner. Imagine creating a message that needs to include a username, the current date, or other data. Formatting allows us to do this simply and elegantly.

Let’s look at the main formatting methods and analyze their advantages and disadvantages to understand when each is best used.

Why do you need string formatting?

String formatting is useful for creating flexible, readable, and dynamically changing text. It allows you to display data, messages, and calculation results by inserting values ​​directly into the text. This is useful in a wide variety of situations, from creating simple notifications to complex reports with large amounts of data.

When can string formatting be useful?

  1. When creating dynamic text, formatting allows you to insert variable and calculation values ​​directly into the string. For example, if you want to display a welcome message with the user’s name or the current date.
  2. For readable and understandable code. Well-formatted lines make code more organized and easier to understand. For example, using f-strings or the method, .format()You can quickly figure out which variables are inserted into the text and where exactly.
  3. Localization and multilingualism. When developing programs that need to support multiple languages, string formatting helps insert the necessary values ​​and translate text. For example, formatting can be used to change text depending on the country.
  4. Save time and reduce errors. Formatting reduces errors, especially those that can occur when manually entering values ​​or working with numbers. For example, we can pre-specify the number of characters after the decimal point or the currency display format.

String formatting methods in Python

Today, Python offers four main string formatting methods that allow you to use variable values ​​and control their representation. The choice of method in each specific case will depend on the requirements for flexibility, readability, and code compatibility.

Let’s look at each of the methods, as well as their pros and cons, in more detail.

% operator

The operator %is an older formatting style that works on the principle of substitution. When using it, you specify which values ​​should be substituted and in what form, using the % symbol and special placeholder characters:

  • %s— inserts a string;
  • %d— integer;
  • %f— floating point number;
  • %x— hexadecimal number, etc.
"string with placeholders" % (values)

Example

name = "John"
age = 28
height = 5.9
formatted_string = "Name: %s, Age: %d, Height: %.1f" % (name, age, height)
print(formatted_string) # Result: Name: John, Age: 28, Height: 5.9

Pros and cons

Although the operator %remains compatible in Python, it is rarely used anymore as other methods provide more functionality.

The main advantage of this method is its support in older versions of Python. This method is available in Python 2 and Python 3, making it suitable for use in older projects.

The main disadvantages of the operator %:

  • Limited capabilities. Unlike other methods, %it does not support nested or named arguments, making it difficult to create complex strings.
  • Low readability. Code %can become difficult to understand, especially if a line contains many variables.
  • Difficulties with formatting options. The method is limited in precision, alignment, and other settings.

Format method

This method .format()allows you to insert values ​​into strings using positional and named arguments. It provides flexible formatting options, such as adjusting alignment, numeric precision, and field widths. This method is convenient for working with various data types and helps create strings with the desired format.

"string with {} for values".format(values)

Examples

name = "Emily"
score = 88.72
formatted_string = "Student: {}, Score: {:.2f}".format(name, score)
print(formatted_string) # Result: Student: Emily, Score: 88.72

The method also .format()has additional capabilities that the operator does not have %:

  • You can specify ordinal numbers of arguments:
    name = "Bob"
    age = 34
    city = "London"
    formatted_string = "Name: {0}, Age: {1}, City: {2}. Age again: {1}".format(name, age, city)
    print(formatted_string) # Result: Name: Bob, Age: 34, City: London. Age again: 34
  • It is possible to use named arguments:
    name = "Sara"
    product = "Laptop"
    price = 799.99
    formatted_string = "Customer: {name}, Product: {product}, Price: ${price:.2f}".format(name=name, product=product, price=price)
    print(formatted_string) # Result: Customer: Sara, Product: Laptop, Price: $799.99
  • You can apply formatting options (we’ll look at them in more detail later):
    name = "John"
    balance = 1234567.8923 # Formatting options: alignment, width, and precision
    formatted_string = "Name: {0:<10}, Balance: {1:,.2f}".format(name, balance)
    print(formatted_string) # Result: Name: John , Balance: 1,234,567.89 

Pros and cons

The method .format()is more flexible and convenient: it allows you to use named and positional arguments and easily customize formatting options.

It is supported in Python 3 and Python 2.7, making it a good choice for cross-versions.

While .format()more readable than %Long lines with multiple arguments can be difficult to understand. It also doesn’t allow direct expressions in placeholders, which reduces its flexibility.

F-strings – String Interpolation

F-strings (formatted strings) are the most modern string formatting method, allowing you to insert values ​​directly into a string using an expression within curly braces {}. This method has been used since Python 3.6, and it is not only convenient but also considered more performant than .format()and %

f"string with {variables} inside"

Examples

name = "Alice"
balance = 1500.2543
formatted_string = f"Hello {name}, your balance is ${balance:,.2f}"
print(formatted_string) # Result: Hello Alice, your balance is $1,500.25 

F-strings also have the following additional features:

  • Expression support:
    a = 10
    b = 5
    formatted_string = f"The sum of {a} and {b} is {a + b}, and their product is {a * b}."
    print(formatted_string) # Result: The sum of 10 and 5 is 15, and their product is 50. 
  • Formatting numbers and dates:
    number = 1234567.89123
    formatted_string = f"The formatted number is {number:,.2f}"
    print(formatted_string)
    # Result: The formatted number is 1,234,567.89

Pros and cons

The advantages of f-strings include simplicity and ease of use, support for expressions, high performance (especially when working with large amounts of data), and wide support for formatting options.

The main disadvantage is that F-strings require Python 3.6 and higher and are not available in earlier versions.

This method is also not suitable for user-input data. Arbitrary expressions can be used in f-strings, which is unsafe when working with user input, as it can lead to errors or vulnerabilities.

Template strings

The class Templateis another formatting method that allows you to create string templates with placeholders of the form $name. This method is especially useful if the template values ​​need to be substituted from a dictionary, making it Templatea good choice for cases where data security is a priority (for example, when creating templates for sensitive data).

Template strings use a dollar sign $followed by a variable name. The method .substitute()substitutes the values ​​into the template:

from string import Template

template = Template(“string with $variable”)
template.substitute(variable=value)

Examples

from string import Template
template = Template("Hello, $name! Your code is $code.")
formatted_string=template.substitute(name="Sarah", code=101)
print(formatted_string) # Результат: Hello, Sarah! Your code is 101. 

Pros and cons

The main advantage of template strings is safety . Unlike f-strings, Templatethey don’t support expressions, making them safer when working with user input.

However, this method lacks support for expressions, complex formatting, and precision settings, making it Templateless flexible than other methods.

Formatting options

We’ve already partially touched on the use of formatting parameters. These parameters determine the appearance of data when output: its width, alignment, precision, style, display type, and even the inclusion of special characters such as currency symbols. Proper use of parameters helps make data output convenient and understandable, especially when working with numbers, dates, or large amounts of text.

Let’s take a look below at what options are supported by different formatting methods.

Operator parameters%

The operator % supports basic parameters: data type ( %s%d%fetc.), precision, and minimum field width. It’s suitable for simple formatting, but doesn’t support alignment or padding, which limits its capabilities compared to other methods. For example:

name = "Alice"
score = 95.6789
print("Name: %s, Score: %.2f" % (name, score)) # Result: Name: Alice, Score: 95.68

Parameters.format()

The method .format()is more flexible and allows you to use all the basic formatting options:

  • Data type : {:.2f}{:.2%}{:e}{:x}for representation in decimal, percentage, scientific notation, and hexadecimal systems.
  • Precision :  {:.2f}– Output floating-point numbers with two decimal places.
  • Width and alignment : {:<10}{:>10}{:^10}for left, right, and center alignment.
  • Fill : {:_>10}– fills the empty spaces on the left with an underscore.
  • Thousands Separator : {:,}– Automatically adds thousands separators.

Example:

name = "Alice"
score = 95.6789
print("Name: {:<10}, Score: {:.2f}".format(name, score))
# Result: Name: Alice , Score: 95.68

f-string options

F-strings support all the same parameters as, .format()but allow variables to be embedded directly into the string, making code easier to write and more readable. Using them also allows you to:

  • Justify and fill : f"{value:0>5}"– fills empty spaces on the left with zeros.
  • Number and date formatting: Options for percentage and scientific notation, thousands separator, and other representation types are supported.

Example:

name = "Alice"
score = 95.6789
print(f"Name: {name:<10}, Score: {score:.2f}")
# Result: Name: Alice , Score: 95.68

Template String Options

Template strings ( string.Template)only support simple substitution of named variables with restrictions on the formatting type. They are not suitable for complex numbers and date formatting.

Conclusion

String formatting in Python is a powerful tool for presenting data in the desired format, and every Python developer should master it. Depending on the task, you can choose the appropriate method: from the simple % operator to the flexible f-strings and the .format(). Each method has its own characteristics, and the choice depends on the code requirements; in most cases, f-strings offer the greatest readability and usability.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?


Explore More IT Terms


Share this term: Facebook X LinkedIn WhatsApp Email

Leave a Reply

Your email address will not be published. Required fields are marked *