sec01 - String formatting [Overview]
スポンサーリンク

What is the format?

In Python, you can not only concatenate strings but also “format” them to make them easier to read.

  • Add commas to numbers to display them as “1,000”
  • Align the number of digits after the decimal point
  • Convert numbers to percentage notation (“0.1234” → “12.34%”)

A function to perform the above “formatting” is available.

In Python, formatting can be done in the following two ways.

  1. Using the format method of strings
  2. Using f-strings (Python 3.6 and later)

In this lecture, we will explain the basic overview of the above two formats, but we will also briefly review how to use the + operator for comparison. This is because the format method and f-string are sometimes used to simply concatenate strings, in addition to “formatting.”

In the following lectures, we will learn more about the format method and f-string. The flow of future lectures is as follows.

  1. String formatting [Overview] (this lecture)
  2. Basics and definition of the format method
  3. Basics and definition of f-strings
  4. String formatting (format specification)

Connecting using the plus operator

Overview of string concatenation with the plus operator

First, let's review the simplest method using the + operator. You can just skim over this part.

name = 'Nico'
age = 10
text = 'I am ' + name + ', ' + str(age) + '.'
print(text)  # I am Nico, 10.

+ operator is easy to understand for beginners, but it only has the function of ‘concatenating’ strings. Therefore, it is difficult to describe format processing, such as separating numbers into groups of three digits with commas in a single line of code.

Summary of plus operator

Key points:

  • If the variable is a string, it can be used as is, but numbers (int/ float) must be converted to strings using str().
  • Simple concatenation is easy to understand.

Advantages:

  • Intuitive, easy to understand, even for Python beginners.
  • No additional symbols or functions are required. (However, str() is often necessary.)

Disadvantages:

  • An error occurs if numbers are not converted to strings.
  • Readability decreases when using long sentences or multiple variables.
  • When attempting to perform format processing, such as digit separation, it cannot be written simply in one line.
スポンサーリンク

Using the format() method

Overview of the format() method

The format method inserts pairs of curly brackets ({}) into the template string. Then, the values of the variables are replaced at the locations of the curly brackets.

template = 'I am {}, {}.'
name = 'Nico'
age = 10
text = template.format(name, age)
print(text)  # I am Nico, 10.

To use the format method, prepare a string such as 'I am {}, {}' as a template. This template string is a regular String type and can use the format method provided for String types. format()replaces the values of the variables specified within the parentheses, but if multiple {}and variables are specified, they are replaced in order from left. In other words, the value of the variable “name” is substituted for the {}immediately after “I am” and the value of the variable “age” is substituted for the {}immediately after “, ”.

Note that the format method does not require you to convert numbers to strings. The numerical value of the “age” variable is processed without error, even if you do not convert it to str(age).

format() method formatting

The format method can perform formatting operations such as digit separation, in addition to concatenating characters, as when using the plus operator.

number = 1234567890
formatted_number = '{:,}'.format(number)
print(formatted_number)  # 1,234,567,890

When you run the above code, you will get the result 1,234,567,890.

It would be difficult to insert commas every three digits using the plus operator, but you can do it in one line using the format method. The format specification is written as {:,}. Enter a colon (:) within the curly braces, and specify the format on the right side of the colon. By adding a comma (,) after the colon, you can obtain a string of digits separated by commas.

For more details on the format specification, please refer to the dedicated lecture.

Summary of format() method

This is a summary of what we have learned so far. There are other ways to write the format method and other useful ways to use it, so let's learn more in a dedicated lecture.

Key points:

  • Numbers are automatically converted to strings (no need for str())
  • Variable values are inserted into {}

Advantages:

  • No need to convert numbers to strings
  • Relatively good readability, even with long sentences
  • Can perform format processing, such as digit grouping
  • Can separate lines defining template strings from lines performing replacements

Disadvantages:

  • You need to get used to the format() syntax.
  • Variables must be passed as arguments to format() (compared to using f-strings).
  • Compared to f-strings, readability may be lower in some cases.

Using f-strings

Overview of f-strings

f-strings are a new string formatting method implemented in Python 3.6. Since they were implemented after the format method, they leverage the advantages of the format method while allowing for more concise writing. They are characterized by their ability to directly embed variables, resulting in high readability. The syntax follows the format f'string{variable}', where the ‘f’ is placed before the quotation marks, and the variable names are directly written inside the curly braces ({}).

name = 'Nico'
age = 10
text = f'I am {name}, {age}.'
print(text)  # I am Nico, 10.

F-strings have the same format as the template strings used in the format method. When defining an f-string, the values of variables are evaluated, and the formatted string is assigned to the “text” variable.

Unlike the format method, there is no need to use the .format() method after the template string, which reduces the amount of code required and improves readability.

f-string format

Like the format method, f-strings can also format characters and numbers. Just like the format method, you specify the format within curly brackets. Here, we will introduce how to display numbers in percentage format.

value = 0.123456
formatted_value = f'{value:.2%}'
print(formatted_value)  # 12.35%

When you run the above code, you will get the result 12.35%.

Regarding the formatting for f-strings, within the curly braces, enter a colon (:) after the variable name, followed by .2% on the right side of the colon. The meaning of .2% after the colon is as follows: .2 indicates that the decimal places should be rounded to two decimal places, and % indicates that the value should be converted to a percentage format.

Summary of f-strings

This is a summary of what we have learned so far. Like the format() method, f-strings also have other ways of writing and useful applications, so let's learn more in a dedicated lecture.

Key points:

  • Write variable names directly inside {}.
  • Numbers can be embedded as they are, without converting them to str().

Advantages:

  • Variable names are visible, making the code easier to read
  • Intuitive and easy to write, with automatic conversion
  • Shorter code than the format method, improving readability

Disadvantages:

  • Cannot be used with Python 3.6 or earlier
  • Unlike the format method, cannot be used when you want to separate the lines that define the template string and the lines that perform the substitution

Overall summary

As a general guideline for concatenating and formatting text, short, simple sentences can be written using the + operator, but if you are using Python 3.6 or later, f-strings are the most convenient option.
The format() method is a good choice for older environments or when you want to separate the definition of template strings from the replacement processing in your code.

MethodDescriptionAdvantagesDisadvantagesTypical Use Case
+ OperatorManually concatenate stringsIntuitive, quick to writeRequires type conversion for numbers, hard to read long stringsShort strings, practice for beginners
format()Replace {} with variables using .format()No need for str(), flexibleSlightly verboseCompatible with Python 3.5 and earlier, dynamic text
f-stringEmbed variables or expressions directly in {}Easy to read, intuitive, all format() benefitsOnly available in Python 3.6+Best for everyday string formatting
スポンサーリンク