Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the detailed explanation of the string formatting format function in Python3

Shulou Source: shulou.com Published: 2022-06-03 00:08:56 09月11日 Update

In this issue, the editor will bring you a detailed explanation of the string formatting format function in Python3. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Format qualifier

Format uses rich "format qualifiers" (syntax is {} with: sign) to complete more detailed formulation of the content that needs to be formatted.

Binary conversion

We can set different characters in the qualifier to format the binary conversion of numbers, and the table corresponding to the base:

Character meaning b binary cUnicode character d decimal integer o octal x hexadecimal, a to f lowercase X hexadecimal, A to F uppercase

N = 99print ('{: B} '.format (N)) print (' {: C} '.format (N)) print (' {: d} '.format (N)) print (' {: o} '.format (N)) print (' {: X} '.format (N)) print (' {: X} '.format (N))

Example result:

1100011c991436363

Fill and align

The character with padding after the: sign can only be one character. If not specified, it is filled with spaces by default, and the padding is often used with alignment. ^, are centered, left-aligned, right-aligned, and followed by width.

N = 99print ('{: > 8} '.format (N)) print (' {: > 8} '.format (N)) print (' {:-

Tags: Character format example precision result content binary function string hexadecimal parenthesis number escape analysis difference rounding professional medium and small binary octal Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Information Apple Shulou Tech Info macOS