Home > Backend Development > Python Tutorial > Detailed introduction to Python string formatting

Detailed introduction to Python string formatting

不言
Release: 2019-03-26 11:15:07
forward
2214 people have browsed it

This article brings you a detailed introduction to the formatting of Python strings. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

I believe that many people use the "%s" % v syntax when formatting strings. PEP 3101 proposes a more advanced formatting method str.format() and becomes the standard in Python 3. To replace the old %s formatting syntax, CPython has implemented this method since 2.6 (other interpreters have not verified it).

format()

The new format() method is actually more like a simplified version of the template engine (Template Engine), with very rich functions.

The replacement variable in the template is surrounded by {} and divided into two parts by :, the second half of which, format_spec, will be discussed separately later.

The first half has three uses:

  • empty
  • The number representing the position
  • The identifier of the keyword

This is consistent with the parameter category of function calls

print("{} {}".format("Hello", "World"))
# 等同于以下几种
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 after login

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

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

Miracle.上海
Miracle 上海
Copy after login

In the template, you can also obtain the attributes or values ​​​​in the variable through .identifier and [key] (it should be noted 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 after login

Forced conversion, you can force the replaced variable through ! r|s|a

  • "{!r}" Call repr() on the variable
  • "{ !s}" Call str() on the variable
  • "{!a}" Call ascii() on the variable

The part after the colon defines the output style

align represents the alignment direction, usually used in conjunction with width, and fill is the filling character (default is blank):

for align, text in zip("<^>", ["left", "center", "right"]):
   # 务必看懂这句话
   print("{:{fill}{align}16}".format(text, fill=align, align=align))

print("{:0=10}".format(100)) # = 只允许数字

# left<<<<<<<<<<<<
# ^^^^^center^^^^^
# >>>>>>>>>>>right
# 0000000100
Copy after login

At the same time, it can be seen that {} can be nested in the style setting, but it must pass the keyword Specified, and can only be nested one level.

The next step is the symbol style: |-|' ' respectively specifies whether the number requires a mandatory symbol (the space means that it will not be displayed when the number is positive but one space will be reserved)

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

# +3.14
# -3.14
# 3.14
Copy after login

Use Whether a prefix symbol is needed to represent numbers in special formats (binary, hexadecimal, etc.)

Comma is also used to represent numbers whether they need to be separated at the thousands place

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

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
Copy after login

Finally, Xiaopang will introduce to you the familiar decimal point precision issues, .n and formatting types.

Only some examples are given here, please refer to the documentation for details:

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

# pi = 3.1, also = 3.141593
Copy after login

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 after login

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 after login

String (default)

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

# 456
Copy after login

This article has ended here. For more exciting content, you can pay attention to the python video tutorial column on the PHP Chinese website!

The above is the detailed content of Detailed introduction to Python string formatting. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template