Labs / Python OOP

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 54 Python Strings and Serialization - String Formatting and the format Method

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents
The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 54 Python Strings and Serialization - String Formatting and the format Method

Abstract:

In Python, string formatting refers to a way of inserting variables into strings, and Python provides multiple methods for string formatting, including the old-style % formatting, the newer str.format method, and f-strings (formatted string literals).

FreakStudio's Blog

Previous Recommendations:

You who are learning embedded systems, don’t you even know Object Oriented yet? ?!

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 00 Introduction to Object Oriented Design Methodology

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 01 Basic Concepts of Object Oriented Programming

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 02 Python Implementation of Classes and Objects - Creating Classes with Python

The most beginner-friendly Object Oriented programming tutorial across the entire network: 03 Python implementation of classes and objects - adding attributes to custom classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 04 Python Implementation of Classes and Objects - Adding Methods to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 05 Python Implementation of Classes and Objects - PyCharm Code Tab

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 06 Python Implementation of Classes and Objects - Data Encapsulation of Custom Classes

The most beginner-friendly Object Oriented programming tutorial across the entire network: 07 Python implementation of classes and objects - type annotations

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 08 Python Implementation of Classes and Objects - @property Decorator

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 09 Python Implementation of Classes and Objects - Relationships Between Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 10 Python Implementation of Classes and Objects - Class Inheritance and Liskov Substitution Principle

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 11 Python Implementation of Classes and Objects - Subclass Calling Parent Class Methods

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 12 Python Implementation of Classes and Objects - Using Python's logging Module to Output Program Runtime Logs

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 13 Python Implementation of Classes and Objects – Installation and Usage of Sourcetrail, a Visual Code Reading Tool

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 14 Python Implementation of Classes and Objects - Static Methods and Class Methods of Classes

The most beginner-friendly Object Oriented programming tutorial across the entire network: 15 Python implementation of classes and objects - the __slots__ magic method

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Internet: 16 Python Implementation of Classes and Objects - Polymorphism, Method Overriding and Open Closed Principle

The most beginner-friendly Object Oriented programming tutorial across the network: 17 Python implementation of classes and objects - duck typing and "file-like object"

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 18 Python Implementation of Classes and Objects - Multiple Inheritance and Drawing Curve Graphs of Serial Port Data with PyQtGraph

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 19 Python Implementation of Classes and Objects – Using PyCharm to Automatically Generate File Comments and function Comments

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 20 Python Implementation of Classes and Objects - Implementation of Composition Relationship and CSV File Saving

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 21 Python Implementation of Classes and Objects - Multi-File Organization: Module and Package

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 22 Python Implementation of Classes and Objects - Exceptions and Syntax Errors

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 23 Python Implementation of Classes and Objects - Throwing Exceptions

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 24 Python Implementation of Classes and Objects - Exception Capture and Handling

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 25 Python Implementation of Classes and Objects - Python Determines Input Data Types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 26 Python Implementation of Classes and Objects - Context Managers and the with Statement

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 27 Python Implementation of Classes and Objects - Implementation of Exception Hierarchy and Custom Exception Classes in Python

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 28 Python Implementation of Classes and Objects - A Comprehensive Summary of Python Programming Principles, Philosophy and Specifications

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 29 Python Implementation of Classes and Objects – Assertions, Defensive Programming and the Usage of the help function

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 30 Python's Built-in Data Types - The object Root Class

The most beginner-friendly Object Oriented programming tutorial across the entire network: 31 Built-in data types in Python - Object and Type

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 32 Python's Built-in Data Types - Class and Instance

The most beginner-friendly Object Oriented programming tutorial on the entire network: 33 Built-in data types in Python – the relationship between objects and types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 34 Python's Built-in Data Types - Commonly Used Composite Data Types in Python: Tuples and Named Tuples

The most beginner-friendly Object Oriented programming tutorial on the entire network: 35 Python's built-in data types - docstrings and the __doc__ attribute

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 36 Python's Built-in Data Type - Dictionary

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 37 Common Composite Data Types in Python - Lists and List Comprehensions

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 38 Common Composite Data Types in Python – Implementing stack, Queue and Deque with Lists

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 39 Common Composite Data Types in Python - Sets

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 40 Common Composite Data Types in Python – Usage of Enumerations and the enum Module

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 41 Common Composite Data Types in Python - Queues (FIFO, LIFO, Priority Queue, Deque and Circular Queue)

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 42 Commonly Used Composite Data Types in Python - Collections Container Data Types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 43 Common Composite Data Types in Python - Extending Built-in Data Types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 44 Python Built-in functions and Magic Methods – Overriding Magic Methods of Built-in Types

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 45 Implementing Common Data Structures in Python – Linked List, Tree, Hash Table, Graph and Heap

The most beginner-friendly Object Oriented programming tutorial across the network: 46 Python function methods and interfaces - functions and event-driven frameworks

The most beginner-friendly Object Oriented programming tutorial across the network: 47 Python function methods and interfaces - Callback function

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 48 Python function Methods and Interfaces - Positional Arguments, Default Arguments, Variable Arguments and Keyword Arguments

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 49 Python function Methods and Interfaces – The Difference Between function and Methods, and Lambda Anonymous Functions

The most beginner-friendly Object Oriented programming tutorial on the entire network: 50 Python function methods and interfaces - Interfaces and Abstract Base Classes

The most beginner-friendly Object Oriented programming tutorial on the entire network: 51 Python function methods and interfaces - Implementing interfaces with Zope

The most beginner-friendly Object Oriented programming tutorial across the network: 52 Python function methods and interfaces - Protocol and interfaces

The most beginner-friendly Object Oriented programming tutorial across the entire network: 53 Python Strings and Serialization - Strings and Character Encodings

More exciting content can be found here:

Speed Up Your Python: A Quick Guide to Python Parallel Computing

Understand the Debugging Principle of CM3 Microcontroller in One Article

After half a month of dedicated work, the ultimate summary of embedded technology stack is now released

The "Martial Arts Manual" for Computer Science Competitions

Avnet ZUBoard 1CG Development Board — A New Choice for Deep learning

Deploy SenseCraft Model to Grove Vision AI V2 Image Processing Module

Document and Code Access:

You can download the document via the following link:

https://github.com/leezisheng/Doc

19

This document mainly introduces how to use Python for Object Oriented programming, and requires readers to have a basic understanding of Python syntax and microcontroller development. Compared with other blogs or books that explain Python Object Oriented programming, this document is more detailed and focuses on embedded host computer applications, taking the common serial port data transmission and reception, data processing, dynamic graph drawing and other functions between the host computer and the slave computer as application examples. Meanwhile, it uses the Sourcetrail code software to visualize the code for reading, so as to facilitate readers' understanding.

The link to obtain the relevant sample code is as follows:

https://github.com/leezisheng/Python-OOP-Demo

Body Text

String formatting is the process of inserting variable values into the placeholder positions within a string, which enables the creation of dynamic text where certain parts may need to be replaced according to different scenarios.

In Python, string formatting methods include the output formatting of the Print function and the Format function formatting.

Use the Print function to implement formatting via format specifiers

Common formatting symbols include:

The sample code is shown below:

print("%c" % 'a')
print("%s" % "string")
print("%s" % 123)   
print("%d" % 100.0) 

The running results are as follows:

123 100

Meanwhile, the conversion specifier can reference dictionary variables.

The format of the specifier is %(mapping_key) flags, where mapping_key specifies the name of the referenced variable, and flags specifies the conversion format.

The sample code is as follows:

print('%(language)s has %(number)01d quote types.'
      % {'language': "Python", "number": 2})

The running results are as follows:

2 0

Format using the format () method

The built-in string class provides the ability to perform complex variable substitution and value formatting via the format () method described in PEP 3101. The Formatter class in the string module allows you to create and customize your own string formatting behaviors using the same implementation as the built-in format () method.

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 54 Python Strings and Serialization - String Formatting and the format Method

The str.format () method and the Formatter class share the same format string syntax (though for the Formatter class, its subclasses can define their own format string syntax). Any string can be turned into a formatted string by calling the format () method. This method returns a new string, in which the special characters will be replaced with the positional arguments and keyword arguments passed into the method. The format method does not limit the number of arguments, and it uses the *args and **kwargs syntax in method parameter passing that we mentioned earlier.

1 2 0 1+2 3

The special symbols that get replaced in a formatted string are the opening and closing curly braces: { and }. We can insert them in pairs, and they will eventually be replaced in order by the positional arguments passed into the str.format method.

The sample code is as follows:

template = "Hello {}, you are currently {}." 
print(template.format('Dusty', 'writing'))

The running results are as follows:

6 0

The str.format () method can use positional arguments or keyword arguments to fill placeholders. Positional arguments are passed in order, while keyword arguments match values using the placeholder names.

The sample code is as follows, and the running result is the same as above.

template = "Hello {0}, you are currently {1}."
print(template.format('Dusty', 'writing'))
template = "Hello {name}, you are currently {doing}."
print(template.format(name='Dusty', doing='writing'))

We don't have to pass only string variables to the format method; any primitive type, such as integers or floating-point numbers that can be printed, is acceptable. More interestingly, complex objects including lists, tuples, dictionaries, and arbitrary objects can all be used; within the format string, we can access variables via indices and object attributes (methods are not allowed). For example, in the following case where we output an email message, we combine the sender and recipient into a tuple in the email address, and store the subject and message in a dictionary, then we can format it like this:

emails = ("a@example.com", "b@example.com")
message = {
            'subject': "You Have Mail!",'message': "Here's some mail for you!"
          }
template = """ 
From: <{0[0]}> 
To: <{0[1]}> 
Subject: {message[subject]} 
{message[message]}"""
print(template.format(emails, message=message))

When we pass the `emails` tuple, we pass a position-based parameter, and these two email addresses can be accessed via `0[x]`, where x can be 0 or 1, corresponding to the first or second element in the tuple. The leading 0 refers to the first positional parameter passed to format (which, in this case, is the `emails` tuple).

When passing the message dictionary, we passed a keyword-based parameter. When accessing the dictionary via string key names, we use message[subject] and message[message]. Note that this is different from the usual way of accessing values in a dictionary — we don’t need to add quotation marks here.

print(message['subject'])

If there are nested data structures, we can even implement multi-level queries. It is not recommended to do so here, as the template string will quickly become incomprehensible in that case. If we have a dictionary containing tuples, we can do it as follows, and the code running result is the same as above:

emails = ("a@example.com", "b@example.com")
message = {
            'emails': emails,
            'subject': "You Have Mail!",
            'message': "Here's some mail for you!"
          }
template = """ 
From: <{0[emails][0]}> 
To: <{0[emails][1]}> 
Subject: {0[subject]} 
{0[message]}"""
print(template.format(message))

Actually, we can also pass any object as an argument to the format function, and then access the object's properties using dot notation. In the following code, we use the format function to output the name, description, and properties/methods of the class.

class SensorClass(SerialClass):
    '''
        Sensor class, inherits from SerialClass
    '''
    ... ...
if __name__ == "__main__":
    template = '''
    Class Name : <{0.__name__}>
    Class Description :  <{0.__doc__}>
    Class Method and Class Properties : <{0.__dict__}>    
    '''
    print(template.format(SensorClass))

The running results are shown as follows:

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 54 Python Strings and Serialization - String Formatting and the format Method

Generally speaking, we use this query method when the object we want to format already exists, rather than creating a class just to use the object in a template.

Introducing variables in template strings is indeed extremely convenient; however, sometimes we need to make appropriate adjustments to these variables to ensure the accuracy of the output results. For example, when calculating accuracy, we may obtain lengthy decimals, but in specific application scenarios, we do not want these detailed values after the decimal point to appear in the final display.

In this case, the str.format () method is particularly practical. It not only allows us to flexibly control the output format, but also provides a wealth of options to meet diverse formatting requirements, such as specifying the number of decimal places, adjusting text alignment, and setting padding characters. With these features, we can control the presentation of output content more precisely, so as to ensure that the information is conveyed accurately and in line with the expected display effect.

The general form of a standard format specifier is as follows:

format_spec     ::=  [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 54 Python Strings and Serialization - String Formatting and the format Method
0
3

Here, the specific meaning of the type parameter is as follows:

(1) s: string, string;
(2) d: decimal integer, decimal number;
(3) i: integer, used the same as %d;
(4) u: unsigned integer, unsigned decimal number;
(5) f: float, floating-point number (6 digits after the decimal point by default);
(6) F: Float, floating-point number (6 digits after the decimal point by default);
(7) e: exponent, represents the number in scientific notation (lowercase e, 6 digits after the decimal point by default);
(8) E: Exponent, represents the number in scientific notation (uppercase E, 6 digits after the decimal point by default);
(9) o: octal, octal number (i.e. 0-7);
(10) x: hexdecimal, hexadecimal number (i.e. 0-9a-f);
(11) X: Hexdecimal, hexadecimal number (0-9A-F);
(12) g: general format, general format, see below...;
(13) G: General format, general format, see below...;
(14) %c: character, converts a decimal number to the corresponding Unicode value;
(15) %r: representation, outputs by calling the __repr__ magic method;
(16) %%: escapes %, outputs a percent sign.

See the example below for details:

price = 49.95
formatted_price = "The price is {:.2f} dollars.".format(price)
print(formatted_price)

The running results are as follows:

49.95 0.2f 0

The 0.2f format specifier following the colon indicates that, from left to right, for values less than 1, it ensures there is a 0 to the left of the decimal point, retains two digits after the decimal point, and formats the input value as a floating-point number.

We can also use placeholder values to make each number occupy a specific number of character positions, which is useful for outputting tabular data, for example:

orders = [('burger', 2, 5),
          ('fries', 3.5, 1),
          ('cola', 1.75, 3)]
print("PRODUCT    QUANTITY    PRICE   SUBTOTAL")
for product, price, quantity in orders:
    subtotal = price * quantity
    print("{0:10s}{1: ^9d} ${2: <8.2f}${3: >7.2f}".format(product, quantity, price, subtotal))

Here, take the formatting operator {1: ^9d} for the quantity variable as an example: d indicates that this is an integer value, and the number 9 specifies that this value should occupy 9 characters.

However, for integers, 0 is used as the default padding character instead of a space. Therefore, we add a space after the colon as a placeholder, and the caret indicates that the number should be aligned in the center. The running result is as follows:

5 2.00 10.00

We can also use < or > to select different alignment modes (left-aligned/right-aligned). Here, we use similar specifiers for the `price` and `subtotal` variables: for `price`, we use `{2:<8.2f}`; for `subtotal`, we use `{3:>7.2f}`. We both specify a space as the padding character, and use the < and > symbols respectively to indicate that the numbers are left-aligned and right-aligned within positions of length 8 and 7. Moreover, each floating-point number retains two decimal places.

For different data types, variations in the "type" character will lead to changes in the output format. We have already learned about the three types s, d, and f, which are used to represent strings, integers, and floating-point numbers respectively. In fact, most other format specifiers can be regarded as variants or extensions of these three basic types. For example, the o type is used to represent octal integers, while the X type is used to represent hexadecimal integers. Additionally, the n type specifier is a special case, as it allows us to separate integers according to local conventions.For floating-point numbers, the % type specifier has a special function: it multiplies the floating-point number by 100 to convert it into a percentage format.

The sample code is as follows:

# Use the thousands separator
number = 1234567
formatted_number = "Formatted number: {:,}".format(number)
print(formatted_number)
# Use percentage format
percentage = 0.25
formatted_percentage = "Formatted percentage: {:.2%}".format(percentage)
print(formatted_percentage)

The running results are as follows:

1 234 567 25.00

It is worth noting that these standard formatting operators can be applied not only to built-in data types, but also to other objects. For non-standard objects, we can define our own format specifiers to meet specific requirements. For example, if we pass a datetime object to format, we can use those specifiers that are available for the datetime.strftime function, such as:

from datetime import datetime

now = datetime.now()
# Format date and time
formatted_date = "Current date and time: {:%Y-%m-%d %H:%M:%S}".format(now)
print(formatted_date)

The output is as follows:

6 2024-04-18 11 51 26 0

It should be noted that these specifiers must follow the correct order, though they are all optional: first comes the fill character, then the alignment, followed by the width, and finally the type.

::=  [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]

In addition to using standard formatting operators, we can also customize formatting operators for our own objects by overriding the special `format` method. For more detailed operations, you can refer to the following documentation: https://peps.python.org/pep-3101/ .

3101 2006 4 16 3.0
The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 54 Python Strings and Serialization - String Formatting and the format Method

Meanwhile, for the opening and closing curly braces: { and }, apart from serving as special substitution symbols in formatted strings, the curly brace characters themselves are also frequently used in strings. We need a way to escape formatting so that they appear purely as curly brace characters rather than being substituted. This can be achieved by doubling the curly braces; for instance, we can use Python to format a basic Java program:

template = """
public class {0} {{
    public static void main(String[] args) {{
        System.out.println("{1}");
    }}
}}"""
print(template.format("MyClass", "print('hello world')"))

The running results are as follows:

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 54 Python Strings and Serialization - String Formatting and the format Method

You can see that the output class name and content have been replaced by the two parameters, and the double curly braces have been replaced with single curly braces, resulting in a piece of valid Java code. Whenever you encounter {{ or }} in the template, which are the symbols used to enclose Java class and method definitions, you should know that the format method will replace them with individual curly brace symbols instead of replacing them with the parameters passed into the format method.

Here, we also summarize the usage methods of some commonly used standard formatting symbols:

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 54 Python Strings and Serialization - String Formatting and the format Method

Generally speaking, the formatting operator is a very powerful tool in Python, which allows us to flexibly control the output format of data as needed. By gaining an in-depth understanding of the usage and characteristics of these operators, we can write clearer, more readable and more efficient code.

347622978