The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 54 Python Strings and Serialization - String Formatting and the format method
Abstracts:
In Python, string formatting is a way of inserting variables into a string, and Python provides several ways of formatting strings, including the old % formatting, the newer methods, and f-string (formatting string literals).
Link to original article:
FreakStudio's Blog
Past Recommendations:
You're learning embedded and you don't know how to be object oriented?
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 00 Introduction to Object-Oriented Design Methods
The network's most suitable for the introduction of object-oriented programming tutorials: 01 Basic Concepts of Object-Oriented Programming
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 02 Python Implementations of Classes and Objects - Creating Classes with Python
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 03 Python Implementations of Classes and Objects - Adding Attributes to Custom Classes
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 04 Python Implementation of Classes and Objects - Adding Methods to Custom Classes
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 05 Python Implementation of Classes and Objects - PyCharm Code Tags
The best object-oriented programming tutorials on the net for getting started: 06 Python implementation of classes and objects - data encapsulation of custom classes
The best object-oriented programming tutorial on the net for getting started: 07 Python implementation of classes and objects - type annotations
The best object-oriented programming tutorials on the net for getting started: 08 Python implementations of classes and objects - @property decorator
The best object-oriented programming tutorials on the net for getting started: 09 Python implementation of classes and objects - the relationship between classes
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 10 Python Implementations of Classes and Objects - Class Inheritance and Richter's Replacement Principle
The best object-oriented programming tutorials on the net for getting started: 11 Python implementation of classes and objects - subclasses call parent class methods
The network's most suitable for the introduction of object-oriented programming tutorials: 12 classes and objects of the Python implementation - Python using the logging module to output the program running logs
The network's most suitable for the introduction of object-oriented programming tutorials: 13 classes and objects of the Python implementation - visual reading code artifacts Sourcetrail's installation use
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 14 Python Implementations of Classes and Objects - Static Methods and Class Methods for Classes
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 15 Python Implementations of Classes and Objects - __slots__ Magic Methods
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 16 Python Implementations of Classes and Objects - Polymorphism, Method Overriding, and the Principle of Open-Close
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 17 Python Implementations of Classes and Objects - Duck Types and "file-like objects"
The network's most suitable for the introduction of object-oriented programming tutorials: 18 classes and objects Python implementation - multiple inheritance and PyQtGraph serial data plotting graphs
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 19 Python Implementations of Classes and Objects - Using PyCharm to Automatically Generate File Annotations and Function Annotations
The best object-oriented programming tutorials on the web for getting started: 20 Python implementation of classes and objects - Combinatorial relationship implementation and CSV file saving
The best introductory object-oriented programming tutorials on the net: 21 Python implementation of classes and objects - Organization of multiple files: modulemodule and packagepackage
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 22 Python Implementations of Classes and Objects - Exceptions and Syntax Errors
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 23 Python Implementation of Classes and Objects - Throwing Exceptions
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 24 Python Implementations of Classes and Objects - Exception Catching and Handling
The best object-oriented programming tutorials on the web for getting started: 25 Python implementation of classes and objects - Python to determine the type of input data
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 26 Python Implementations of Classes and Objects - Context Managers and with Statements
The best introductory object-oriented programming tutorials on the web: 27 Python implementation of classes and objects - Exception hierarchy and custom exception class implementation in Python
The best object-oriented programming tutorials on the net for getting started: 28 Python implementations of classes and objects - Python programming principles, philosophies and norms in a big summary
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 29 Python Implementations of Classes and Objects - Assertions and Defensive Programming and Use of the help Function
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 30 Python's Built-In Data Types - the root class of object
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 31 Python's Built-In Data Types - Object Object and Type Type
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 32 Python's Built-in Data Types - Class Class and Instance Instance
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 33 Python's Built-In Data Types - The Relationship Between the Object Object and the Type Type
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 34 Python's Built-In Data Types - Python's Common Compound Data Types: Tuples and Named Tuples
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 35 Python's Built-In Data Types - Document Strings and the __doc__ Attribute
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 36 Python's Built-In Data Types - Dictionaries
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 37 Python's Common Composite Data Types - Lists and List Derivatives
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 38 Python's Common Composite Data Types - Using Lists to Implement Stacks, Queues, and Double-Ended Queues
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 39 Python Common Composite Data Types - Collections
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 40 Python's Common Compound Data Types - Enumeration and Use of the enum Module
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 41 Python's Common Composite Data Types - Queues (FIFO, LIFO, Priority Queue, Double-Ended Queue, and Ring Queue)
The best introductory object-oriented programming tutorials on the web: 42 Python commonly used composite data types-collections container data type
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 43 Python's Common Composite Data Types - Extended Built-In Data Types
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 44 Python Built-In Functions and Magic Methods - Magic Methods for Rewriting Built-In Types
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 45 Python Implementations of Common Data Structures - Chain Tables, Trees, Hash Tables, Graphs, and Heaps
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 46 Python Function Methods and Interfaces - Functions and Event-Driven Frameworks
The network's most suitable for the introduction of object-oriented programming tutorials: 47 Python function methods and interfaces - callback function Callback
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 48 Python Function Methods and Interfaces - Positional Arguments, Default Arguments, Variable Arguments, and Keyword Arguments
Best Object-Oriented Programming Tutorials on the Net for Getting Started: 49 Python Functions Methods and Interfaces - Difference between Functions and Methods and lamda Anonymous Functions
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 50 Python Function Methods and Interfaces - Interfaces and Abstract Base Classes
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 51 Python Function Methods and Interfaces - Implementing Interfaces with Zope
Best Object-Oriented Programming Tutorials for Beginners on the Web: 52 Python Functions Methods and Interfaces-Protocol Protocols and Interfaces
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 53 Python Strings and Serialization - Strings and Character Encoding
More highlights to watch:
Accelerating Your Python: A Quick Guide to Python Parallel Computing
Understanding CM3 MCU Debugging Principles in One Article
Liver half a month, embedded technology stack summary out of the big
The "Secrets of the Martial Arts" of the Computer Competition
A MicroPython open source project collection: awesome-micropython, including all aspects of Micropython tool library
Avnet ZUBoard 1CG Development Board - A New Choice for Deep Learning
SenseCraft Deploys Models to Grove Vision AI V2 Image Processing Module
Documentation and code acquisition:
The following link can be accessed to download the document:
/leezisheng/Doc
This document mainly introduces how to use Python for object-oriented programming, which 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, with common serial port data sending and receiving, data processing, and dynamic graph drawing as application examples for the host computer and the lower computer, and using Sourcetrail code software to visualize and read the code for readers' easy understanding.
The link to get the relevant sample code is below:/leezisheng/Python-OOP-Demo
main body (of a book)
String formatting is the process of inserting variable values into placeholder positions in a string. This enables the creation of dynamic text, some parts of which may need to be replaced depending on the situation.
String formatting in Python includes output formatting by the Print function and formatting by the Format function.
Formatting with Print Function Formatting Symbols
Common formatting symbols include:
- (1) %c: Formatting characters and their ASCII codes;
- (2) %s: format string;
- (3) %d: Formatted integer;
- (4) %u: format unsigned integer;
- (5) %o: Formats an unsigned octal number;
- (6) %x: Formats an unsigned hexadecimal number;
- (7) %f: formatting floating-point numbers, you can specify the precision after the decimal point;
- (8) %e: Format floating point numbers in scientific notation;
- (9) %g: Short for %d and %e.
The sample code is shown below:
print("%c" % 'a')
print("%s" % "string")
print("%s" % 123)
print("%d" % 100.0)
The results of the run are as follows:
Also the conversion specifier can refer to dictionary variables.
The format of the converter is %(mapping_key)flags, mapping_key specifies the name of the referenced variable, and flags specifies the format of the conversion.
The sample code is as follows:
print('%(language)s has %(number)01d quote types.'
% {'language': "Python", "number": 2})
The results of the run are as follows:
Formatting with the format() method
The built-in string class provides the ability to perform complex variable substitution and value formatting through the use of the format() method described in PEP 3101. the Formatter class in the string module allows you to create and customize your own string formatting behavior using the same implementation as the built-in format() method.
() method shares the same format string syntax as the Formatter class (although for the Formatter class, its subclasses can define their own format string syntax). Any string can be formatted by calling the format() method. This method returns a new string with the special characters replaced with the arguments and keywords passed to the method. format method does not limit the number of arguments, and it uses the *args and **kwargs syntax we mentioned earlier for method passing.
The special symbols that are replaced in the format string are the open and closed braces: { and }. They can be inserted in pairs, and will eventually be replaced by the positional parameters passed in the method, in that order.
The sample code is as follows:
template = "Hello {}, you are currently {}."
print(('Dusty', 'writing'))
The results of the run are as follows:
The () method can be populated with placeholders using either positional or keyword arguments. Positional arguments are passed sequentially, while keyword arguments use placeholder names to match values.
Sample code is as follows, run the results as above.
template = "Hello {0}, you are currently {1}."
print(('Dusty', 'writing'))
template = "Hello {name}, you are currently {doing}."
print((name='Dusty', doing='writing'))
We can't just pass string variables to the format method; any basic type, such as an integer or float that can be printed out, will do. More interestingly, complex objects, including lists, tuples, dictionaries, and arbitrary objects can be used; in the format string we can access the variable by index and by the object's properties (not methods). For example, in the following example, we output an email message, which we format by combining the sender and recipient into a tuple in the email address and storing the subject and message in a dictionary:
emails = ("a@", "b@")
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((emails, message=message))
We pass the emails tuple with a location-based argument, and the two email addresses can be obtained with 0[x], where x can be either 0 or 1, indicating the first or second element in the tuple. The first 0 represents the first positional parameter passed into format (in this case the emails tuple).
We pass a keyword-based argument when passing the message dictionary, where the dictionary is accessed via a string key name using message[subject] and message[message], Notemeaning here is different from the usual access to the values in the dictionary, we don't need to put quotes.
print(message['subject'])
With nested data structures, we can even implement multi-level queries.It is recommended not to do this here, as the template strings would then quickly become unintelligible.If we have a dictionary containing tuples, we can do this, and the code runs as above:
emails = ("a@", "b@")
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((message))
In fact, you can pass any object as an argument to the format function and then access the properties of the object using dot notation. In the following code, we have used the format function to output the class name, description and properties/methods.
class SensorClass(SerialClass):
'''
Sensors,inherited fromSerialClass
'''
... ...
if __name__ == "__main__":
template = '''
Class Name : <{0.__name__}>
Class Description : <{0.__doc__}>
Class Method and Class Properties : <{0.__dict__}>
'''
print((SensorClass))
The results of the run are shown below:
Typically, we would use this query in cases where the object you want to format already exists, but would not create a class just to use the object in a template.
Introducing variables into template strings is indeed extremely convenient, however, sometimes we need to adjust these variables appropriately in order to ensure the accuracy of the output. For example, when performing accuracy calculations, we may get lengthy decimals, but in a particular application scenario, we don't want these exhaustive decimal values to appear in the final presentation.
At this point, the () method is particularly useful. Not only does it allow us to flexibly control the formatting of the output, but it also provides a number of options to meet different formatting needs, such as specifying the number of decimal places, adjusting text alignment, and setting fill characters. With these features, we can more precisely control the presentation of the output to ensure that the message is conveyed accurately and in line with the desired presentation.
The general form of a standard format descriptor 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" | "%"
Here, the type parameter has the following meaning:
(1) s: string, string.
(2) d: decimal integer, decimal number.
(3) i: integer, same as %d.
(4) u: unsigned integer, unsigned decimal number.
(5) f: float, floating point number (retains 6 decimal places by default); (6) F: Float, floating point number (retains 6 decimal places by default).
(6) f: float, floating point number (6 decimal places are preserved by default); (7) e: exponent, exponential number (6 decimal places are preserved by default).
(7) e: exponent, expresses a number in scientific notation (lowercase e, defaults to 6 decimal places); (8) E: Exponent, exponentifies a number in scientific notation (lowercase e, defaults to 6 decimal places).
(8) E: Exponent, expresses a number as scientific notation (uppercase E, 6 decimal places by default); (9) o: octal, expresses a number as a scientific notation (lowercase e, 6 decimal places by default); (10) o: octal, expresses a number as a scientific notation (lowercase e, 6 decimal places by default)
(9) o: octal, octal number (i.e., 0-7); (10) x: hexdecimal, a number in octal notation (i.e., 0-7).
(10) x: hexdecimal, hexadecimal number (i.e. 0-9a-f).
(11) x: Hexdecimal, hexadecimal number (i.e. 0-9a-f).
(12) g: general format, general format, see below... ;)
(13) G: General format, General format, see the following... ;^: G: General format, General format, see the following... ;)
(14) %c: character, converts a decimal number to its corresponding unicode value.
(15) %r: representation, call the __repr__ magic method to output.
(16) %%: escape %, output percent signs.
See below for an example:
price = 49.95
formatted_price = "The price is {:.2f} dollars.".format(price)
print(formatted_price)
The results of the run are as follows:
The 0.2f formatting indicator after the colon indicates that, from left to right, for values less than 1, make sure there is a 0 to the left of the decimal point; keep two digits after the decimal point to format the input value as a floating-point number.
We can also make each number occupy a specific number of character positions by using placeholder values. This 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, the formatting operator {1: ^9d} for the quantity variable is used as an example. d means that this is an integer value, and the number 9 means that the value needs to occupy 9 characters.
But for integers, the default is to fill them with zeros instead of spaces. So we add a space after the colon as a placeholder. The insertion symbol indicates that the number is aligned in a centered manner. The result is as follows:
We can also use < or > to select a different alignment (left/right). Here, we use similar indicators 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, but use the < and > symbols to indicate that the numbers are left- and right-aligned for lengths of 8 and 7, respectively. Also, each floating-point number retains two decimal places.
For different data types, the difference in the "type" character results in a change in the output format. We have already learned about the three types s, d, and f, which are used to represent strings, integers, and floats, respectively. In fact, most other formatting indicators can be thought of as variants or extensions of these three basic types. For example, type o is used to represent octal integers, while type X is used to represent hexadecimal integers. In addition, the n type indicator has a special presence that allows us to separate integers according to our local conventions. In the case of floating-point numbers, the % type indicator has a special feature that multiplies a floating-point number by 100, thus converting it to percent form.
The sample code is as follows:
_# Using the thousands separator_
number = 1234567
formatted_number = "Formatted number: {:,}".format(number)
print(formatted_number)
_# Use of percentage format_
percentage = 0.25
formatted_percentage = "Formatted percentage: {:.2%}".format(percentage)
print(formatted_percentage)
The results of the run are as follows:
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 formatting indicators to meet specific needs. For example, if we pass a datetime object to format, we can use indicators that can be used in functions, such as:
from datetime import datetime
now = ()
_# Formatting dates and times_
formatted_date = "Current date and time: {:%Y-%m-%d %H:%M:%S}".format(now)
print(formatted_date)
The output is as follows:
One thing to note: these indicators must be in the correct order, though they are all optional: first the padding character, second the alignment, then the size, and finally the type.
::= [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]
In addition to using the standard formatting operators, we can also customize the formatting operators for our own objects by overriding the format special method, which can be viewed in more detail in the following documentation:/pep-3101/。
Meanwhile, the open and closed braces: { and } are commonly used in strings by the braces symbols themselves, in addition to being special symbols that are replaced in formatted strings. We need to have a way to skip the formatting and just appear as the brace symbols themselves, rather than being replaced. We can do this by repeating the curly braces twice; for example, we can format a basic Java program in Python:
template = """
public class {0} {{
public static void main(String[] args) {{
("{1}");
}}
}}"""
print(("MyClass", "print('hello world')"))
The results of the run are as follows:
You can see that the class name and content of the output has been replaced with two parameters, and the double braces have been replaced with single braces, resulting in a legal piece of Java code. Whenever you see {{ or }} in a template, that's the notation used to enclose Java class and method definitions. We know that the format method replaces them with a single brace symbol, not with the parameters passed into the format method.
Here, we also summarize some of the common ways to use the formatting standard symbols:
Overall, formatting operators are a very powerful tool in Python, allowing us to flexibly control the format of data output as needed. By taking a deeper look at the usage and characteristics of these operators, we can write clearer, more readable, and more efficient code.