How to format strings in Python

Read Time:9 Minute, 56 Second

Table of Contents

Python string formatting is a valuable tool for Python programmers daily. Strings appear to be formatted similarly in each coding language. It’s also a big reason we utilize scripting languages in the first place.

The f string method and .format() and concatenation are the most popular approaches to formatting strings. With most legacy libraries supporting Python3, we may see the Python2 syntax fade away.

We’ll look at how to format strings in Python in this tutorial. Dynamically infusing things into a string and presenting it is known as string formatting. You can do string formatting in five different ways:

  • Using the percent operator to format.
  • The .format() string method is used to format the data.
  • f-strings are string literals that are used to format data.
  • String Template Class Formatting
  • Using Concatenation

So we’ll look at all of the methods described above. And identify which string formatting style is the best.

String format() method in Python

The .format() function was introduced in Python 3 to make it easier to handle sophisticated string formatting. Formatters work by inserting replacement fields and placeholders into a string and using the str.format() function. The value we want to put in the placeholders concatenated with the text supplied to the format method as parameters.

SUGGESTED READ

Syntax:

Example: Formatting any string using the format() method

Compared to the placeholder approach, the .format() method provides a lot of advantages:

  1. We can use an index-based location to insert an object:
  1. Using specified keywords, we can subsequently insert objects:
  1. To avoid repetition, we can reuse the added objects:

With the .format() method, you can get float precision:

The type is highly ideal to use with format codes:

SUGGESTED READ

  • ‘d’ for integers
  • ‘f’ for floating-point numbers
  • ‘b’ for binary numbers
  • ‘o’ for octal numbers
  • ‘x’ for octal hexadecimal numbers
  • ‘s’ for string ‘e’ for floating-point in an exponent format

Example

Inside the placeholder, type the price in fixed point, two-decimal format:

The format() method formats and inserts the provided value(s) into the string’s placeholder. On the other hand, curly brackets are responsible for defining the placeholder. In the Placeholder section below, you may learn more about the placeholders.

The format() method return value is a formatted string.

The syntax is as follows:

SUGGESTED READ

Parameter Values Parameter Description
value 1, value 2… Required. There should be one or more values prepared and put into the string. The values can be a comma-separated list of values, a key=value list, or a combination of both. You can use any data type for the values.

The placeholders

Named indices like price, numbered indexes like {0} and you can even use empty placeholders can be used to identify placeholders {}.

Changing the placeholder values:

Types of Formatting

You can add a formatting type to the placeholders for result formatting:

:< Left is responsible for aligning the result within the available space

:> The right has to align the result within the available space

SUGGESTED READ

:^ Center’s mandate is to align the result within the available space

:= Places the sign to the leftmost position

:+ Using the plus sign indicates whether the outcome is positive or negative

:- Use of a minus is solely for negative values

: Use space to insert an extra space before positive numbers (and a minus sign before negative numbers)

SUGGESTED READ

:, Use a comma as a thousand separator

:_ Use an underscore as a thousand separator

:b Binary format

:c Is responsible for converting the said value into the corresponding Unicode character

:d Decimal format

SUGGESTED READ

:e Scientific format, with a lower case e

:E Scientific format, with an upper case E

:f Fixpoint number format

:F Fixpoint number format, in uppercase format (show inf and nan as INF and NAN)

:g General format

SUGGESTED READ

:G General format (using an upper case E for scientific notations)

😮 Octal format

😡 Hex format, lower case

:X Hex format, upper case

:n Number format

SUGGESTED READ

:% Percentage format

Example:

vs.

Using the percent(%) operator to format a string

It’s the most traditional way to format strings. The modulo percent operator is used here. The “string-formatting operator” is another name for the modulo percent. In fact, the percent operator can access a unique built-in operation in Python strings. It makes it very simple to do simple positional formatting. If you’ve ever used a printf-style function in C, you’ll immediately realize how this works.

Example: Using the percent operator to format a string

SUGGESTED READ

You can also inject many texts simultaneously and put objects in the string using variables.

Example: Injecting multiple strings using the % operator

‘%s’ is used to inject strings in the same way that ‘% d’ is used to inject integer numbers, ‘% f’ is used to inject floating-point values, and ‘% b’ is used to inject binary format.

Precision floats using the placeholder method:

The format for floating-point numbers is %a.bf. If the complete number does not include this many digits, a would-be the minimal number of digits in the string; these could be padded with white space. Closely related, bf denotes the number of digits following the decimal point.

SUGGESTED READ

Consider the following examples:

Example 1: Float point precision using the % operator

Example 2: You can use multiple format conversion types in a single print statement

Example:

We’re telling Python were to substitute the value of name, represented as a string, with the %s format specifier.

Other format specifiers are available for controlling the output format. For example, to create adequately written tables and reports, you can convert integers to hexadecimal notation or include whitespace padding. To convert an int value to a string and represent it as a hexadecimal number, use the % x format specifier:

If you want to make numerous substitutions in a single string, the “old style” string formatting syntax changes slightly. Because the percent operator only accepts one parameter, the right-hand side must be wrapped in a tuple, as shown below:

SUGGESTED READ

If you supply a mapping to the percent operator, you can additionally refer to variable substitutions by username in your format string:

It makes it easy to maintain and adjust your format strings in the future. You don’t have to worry about the order in which the values are passed. That is as far as matching the order in which they are referenced in the format string. The disadvantage is that this method necessitates a little more typing.

I’m sure you’ve wondered why this printf-type string formatting is referred to as “old style.” It was technically supplanted by Python 3’s “new style” formatting, which we’ll discuss next.

Using F-strings to format a string

Literal String Interpolation, or F-strings, is a new string formatting mechanism proposed by PEP 498. The reason for this is the leading f character preceding the string literal. F-strings are designed to make string interpolation easier.

Prefix the string with the letter ” f ” to make an f-string. You can format the string itself in the same way that you would with str.format (). F-strings are a quick and easy technique to format strings by embedding python expressions inside the string literal.

SUGGESTED READ

Example: String Formatting with F-Strings

This new formatting syntax is exceptionally versatile and straightforward to use. You may also use it to insert arbitrary Python expressions and perform arithmetic calculations.

Example: Arithmetic operations using F-strings

You can also use Lambda expressions in f-string formatting.

Example: Lambda Expressions using F-strings

The precision of floats in the f-String method:

Example: Float Precision using F-strings

String Template Class

Template Class in the String module allows us to construct reduced output specification syntax. $ forms placeholder names with valid Python identifiers in this format (alphanumeric characters and underscores). Enclosing the placeholder in braces can be followed by more alphanumeric letters without any gaps. When you type $$, you get a single escaped $:

Example: Formatting string using Template Class

SUGGESTED READ

Using Concatenation to Format a String

It is the most basic – and consequently the most straightforward – approach to learning. It’s also how we prefer to instruct someone new to coding. It’s simple to understand without a prior understanding of coding because the pieces are in literal sequence, and the ‘+’ operators are used.

The examples shown above construct a formatted string by joining variables with the addition operator. It’s important to remember that we’ll need to convert all variables to strings. The variable company_name is already a string, and the c_year is an integer.

Which type of string formatting is the most effective?

Both percent -formatting and str.format() are slower and less effective than f-strings (). Expressions in f-strings are evaluated at runtime, and we can embed expressions within f-strings using a fundamental and straightforward syntax.

The phrases inside the braces are evaluated at runtime, then combined with the f-string string’s component, and returned to the final string.

Is it essential to learn and use all of these string formatting methods?

When learning Python, you’ll need to know all of this. Even if you don’t use the old string formatting often, it’s still used in some more senior forums, Stack Overflow articles, and many older Machine Learning frameworks. As a result, knowing them will help you recognize what’s going on and maybe debug an issue.

SUGGESTED READ

You can use any of the other three methods we described here to format your strings in Python. Choose the one that best fits the situation and even your mood on that day!

When working with short and simple sentences, the + comes in handy. It’s also helpful in creating debugging states when working on a modest project. For example, we could utilize the + operator to create a basic number guessing game.

The .format() or f string methods may be preferable when adding logging statements because they make your statements more modular. It will also be simpler to describe the data type’s precision and formatting.

Conclusion

Surprisingly, there are multiple approaches to string formatting in Python. Each strategy has its own set of advantages and disadvantages. Which method you should choose will be determined by your use case.

When you’re coding in Python, you’ll have to format strings all the time. We must eventually print or display every variable, tuple, dictionary, and logic that we define. And each of these, without exception, requires us to convert the required output into a string before printing it or using the appropriate Python function to show it.

SUGGESTED READ

Using the traditional % strategy was more common in Python2 when it was still a young and emerging language. For experienced coders with a C programming background, it’s a simple approach to grasp. On the other hand, .format() is used by many Python programmers because this makes things easier for you. F strings are the newest technique that Python3 supports, and they’re quickly gaining popularity.

Template strings is a technique available as a class in the Python standard library’s string module. It’s imported as a module, replacing placeholders with the .substitute() method.

Source: https://www.codeunderscored.com/how-to-format-strings-in-python/