sec01 - Basics of f-strings

In this lecture, you will learn the basics and definition of the f-string notation. For formatting specifications such as digit separation, the content is the same as the format method, so you will learn more about it in the lecture “String formatting (format specification)”.

スポンサーリンク

Basics of f-strings

f-strings are a new string formatting method implemented in Python 3.6 that leverages the benefits of the format method while allowing for more concise writing. When writing code, it is generally recommended to use f-strings whenever possible and only use the format method in cases where f-strings are not applicable or would result in reduced readability. It is important to understand the characteristics of each and use them appropriately.

The difference between the format method and f-strings is that the format method allows you to separate the lines for defining the template string and the replacement process for {} (when to use .format()). On the other hand, f-strings combine the ‘definition’ and ‘replacement of {} with actual values’ into a single line. This means that while f-strings offer the advantage of improved readability, they cannot be used in cases where you specifically want to separate these steps into separate lines.

A scenario where the format method is preferred over f-strings is when you need to configure various settings according to the usage environment and then operate the system. In such cases, it is common to separate the code into a file that defines the various settings (config.py) and a file that performs some processing (generate_something.py). By separating the files, you can avoid modifying the code that performs the processing and instead simply update the contents of “config.py” according to the usage environment. (In this case, the template strings are defined within “config.py.”) When writing code by separating files in this manner, the only option is to use the format method, which allows you to define the template strings and perform the replacement processing on separate lines.

Definition of f-string

f-string is defined in the format f'...{variable}'. Precede the quotation with “f” and write the variable name directly inside curly brackets({}).

Write the code as follows.

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

The definition of f-string is written in the third line of the above code. In this one line, the variables "name" and "age" are evaluated and replaced, and the generated string is assigned to the variable “text.”

When defining f-strings, you can use single quotes', double quotes", or triple quotes''',""".

スポンサーリンク