It is believed that many people use the “%s” % v syntax when formatting strings. PEP 3101 introduced a more advanced formatting method str.format() that became standard in Python 3 to replace the old %s formatting syntax. CPython has implemented this approach since 2.6 (other interpreters are unverified).

format()

The new format() method is more like a shortened version of Template Engine, with lots of functionality.

The substitution variables in the template are surrounded by {} and divided into two parts by:, the latter part of which format_spec is discussed separately later.

The first half can be used in three ways:

  • empty
  • A number representing a location
  • An identifier that represents the keyword

This is consistent with the parameter category of the function call

print("{} {}".format("Hello"."World"))
# is 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
Copy the code

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

print("{author}.{city}".format(**{"author": "Miracle"."city": "Shanghai"}))
print("{} {}".format(*["Miracle"."Shanghai"[)) Miracle. Shanghai MiracleCopy the code

It is also possible to retrieve attributes or values within a variable in a template using.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
Copy the code

Cast, can pass! + r | s | a way to replace the variables to coercion

  • “{! R}” call repr() on the variable
  • “{! Call STR () on the variable
  • “{! A}” call ASCII () on a variable

The part after the colon defines the style of the output

Align stands for alignment and is usually used with width, while fill is the filled character (default is blank) :

for align, text in zip("< ^ >"["left"."center"."right") :# Make sure you 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
Copy the code

You can also see that {} can be nested within the style Settings, but it must be specified by keyword and can be nested only at one level.

Followed by the symbol style: + | | ‘respectively specified number whether need mandatory symbols (including space refers to the positive number does not show + but keep a space)

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

# + 3.14
# 3.14
# 3.14
Copy the code

Whether a prefix is required for numbers in a particular format (binary, hexadecimal, etc.)

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

0 corresponds to the preceding {:0=} right-aligned and fills the void with 0

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

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

Finally, fat to introduce the familiar decimal point precision problem,.n and formatting type.

Here are just a few examples, details can be found in the documentation:

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

# pi = 3.1, also = 3.141593
Copy the code

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
Copy the code

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%
Copy the code

String (default)

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

# 456
Copy the code

Follow the public account “Python Column” and reply to “Tencent Architecture Resources 1” in the background to get a full set of big data learning resources package organized by Tencent architects!