[Python] After reading this article, you still don’t know how to format strings

Hits: 0

🎶Blog homepage: The blog homepage of the program is on the way
🦋Welcome to follow🖱Like👍favorites🌟Message
💖Series of columns: Python learning 🌠First release time: April 26, 2022

Table of contents

foreword

Why is there a formatting problem with [string] types? For example, a program wants to output the following:
“2016-12-31: The CPU usage of the computer PYTHON is 10%.”

Among them, the content of the underline may change, and it needs to be filled with the operation result of a specific function, and finally the above format string is formed as the output result. String formatting is used to solve the formatting arrangement when strings and variables are output at the same time.

String is one of the main forms for programs to output operation results to consoles, networks, files and other media. In order to provide better readability and flexibility, the formatting of string types is one of the important contents of using string types. one. The Python language supports two string formatting methods at the same time. One is similar to the formatting method of the printf() function in the C language . Supporting this method is mainly considered to be consistent with the programming habits of a large number of C language programmers; the other uses a special str .format() formatting method. Since complex data types (such as lists and dictionaries) that are closer to natural language in Python cannot be well expressed by C -like formatting methods, Python has not improved C -style formatting methods in subsequent versions. The Python language will mainly use the format() method for string formatting. All examples in this article use this method, and readers are advised to use this method as much as possible.

Extension: The
printf() function is the main function of outputting information to the console in the C language, similar to the print() function in the Python language .

Basic usage of format() method

The basic usage format of the string format() method is as follows: