Python | the formatting of Python strings. It's enough to read this article

It is believed that many people use the syntax of "% s"% v "when formatting strings. PEP 3101 proposes a more advanced formatting method str.format() and has become the standard of Python 3 to replace the old% s formatting syntax. CPython has implemented this method since 2.6 (other interpreters have not been verified).

 

format()

The new format() method is actually more like a simplified version of the Template Engine, which has rich functions.

The replacement variables in the template are surrounded by {} and are divided into two parts by: the latter part is format_spec will be discussed separately later.

The first half has three uses:

  • empty

  • Number representing location

  • Identifier representing keyword

This is consistent with the parameter category of the function call

print("{} {}".format("Hello", "World"))
# Equivalent to the following
print("{0} {1}".format("Hello", "World"))
print("{hello} {world}".format(hello="Hello", world="World"))
print("{0}{1}{0}".format("H", "e"))

# Hello World
# Hello World
# Hello World
# HeH

In addition, just like unpacking function parameters, unpacking can also be used directly in format()

print("{author}.{city}".format(**{"author": "Miracle", "city": "Shanghai"}))
print("{} {}".format(*["Miracle", "Shanghai"]))

Miracle.Shanghai
Miracle Shanghai

In the template, you can also use Get the attribute or value in the variable by identifier and [key] (note that "{} {}" is equivalent to "{0} {1}")

data = {'author': 'Miracle', 'like': 'papapa'}
print("Author: {0[author]}, Like: {0[like]}".format(data))
langs = ["Python", "Ruby"]
print("{0[0]} vs {0[1]}".format(langs))

print("\n====\nHelp(format):{.__doc__}".format(str.format))

# Name: Python, Score: 100
# Python vs Ruby

# ====
# Help(format):
#  S.format(*args, **kwargs) -> str

Forced conversion can be passed+ r|s|a is used to cast the replaced variable

  • '{! r}' calls repr() on a variable

  • '{s}' calls str() on a variable

  • '{! A}' calls ascii() on a variable

The section after the colon defines the style of the output

align stands for the alignment direction, which is usually used in conjunction with width, while fill is the filled character (blank by default):

for align, text in zip("<^>", ["left", "center", "right"]):
    # Be sure to understand this sentence
    print("{:{fill}{align}16}".format(text, fill=align, align=align))

print("{:0=10}".format(100)) # =Only numbers are allowed

# left<<<<<<<<<<<<
# ^^^^^center^^^^^
# >>>>>>>>>>>right
# 0000000100

At the same time, it can be seen that {} can be nested in the style setting, but it must be specified through keyword, and can only be nested one layer.

Next is the symbol style: + | - | ', respectively specify whether the number needs a mandatory symbol (where space means that + is not displayed when the number is positive, but one space is reserved)

print("{0:+}\n{1:-}\n{0: }".format(3.14, -3.14))

# +3.14
# -3.14
# 3.14

Whether prefix symbols are required for numbers in special formats (binary, hexadecimal, etc.)

Commas are also used to indicate whether numbers need to be separated in thousands

0 is equivalent to the previous {: 0 =} right aligned and filled with 0

print("Binary: {0:b} => {0:#b}".format(3))
print("Large Number: {0:} => {0:,}".format(1.25e6))
print("Padding: {0:16} => {0:016}".format(3))

# Binary: 11 => 0b11
# Large Number: 1250000.0 => 1,250,000.0
# Padding:                3 => 0000000000000003

Finally, let's introduce the familiar decimal point accuracy n and format type.

Here are only some examples. For details, please refer to the document:

from math import pi
print("pi = {pi:.2}, also = {pi:.7}".format(pi=pi))

# pi = 3.1, also = 3.141593

Integer

for t in "b c d #o #x #X n".split():
    print("Type {0:>2} of {1} shows: {1:{t}}".format(t, 97, t=t))

# Type  b of 97 shows: 1100001
# Type  c of 97 shows: a
# Type  d of 97 shows: 97
# Type #o of 97 shows: 0o141
# Type #x of 97 shows: 0x61
# Type #X of 97 shows: 0X61
# Type  n of 97 shows: 97

Float

for t, n in zip("eEfFgGn%", [12345, 12345, 1.3, 1.3, 1, 2, 3.14, 0.985]):
    print("Type {} shows: {:.2{t}}".format(t, n, t=t))

# Type e shows: 1.23e+04
# Type E shows: 1.23E+04
# Type f shows: 1.30
# Type F shows: 1.30
# Type g shows: 1
# Type G shows: 2
# Type n shows: 3.1
# Type % shows: 98.50%

String (default)

try:
    print("{:s}".format(123))
except:
    print("{}".format(456))

# 456

Tags: Python string

Posted by nevynev on Sun, 17 Apr 2022 21:41:33 +0930