Discussion on Python format Function

  • 2021-12-11 08:24:24
  • OfStack

Summary of format function of directory Python string

format Function of Python String

The format () function is used to collect the positional and key field arguments that follow and fill the placeholders in the string with their values. The usual format is as follows:

'{pos or key : fill, align, sign, 0, width, .precision, type}'.format(para1...)

The whole curly brace is a placeholder, and the position before the colon or keyword is used to locate the parameter of format function, and after the colon is used to format the parameter, where each one is optional.

1. fill is used to specify padding characters and defaults to spaces

2. align specifies the alignment: > Aligned to the right, < Left-aligned, ^ center-aligned

3. sign specifies whether to keep signs: + to keep signs and-to keep only minus signs

4. If 0 is added before the width, it means it is filled with 0

5. width specified width

6. precision Specification Accuracy

7. type specifies the type, for example, b is binary and x is 106

1 Some examples are as follows:


# Fill with location 
print(
    'Hello,{0}. My name is {1}. How\'s it going?'.format('Hialry','Vergil')
    #Hello,Hialry. My name is Vergil. How's it going?
)
# If the fill location is not specified in the format, it will be filled in sequence 
print(
    '{}--{}--{}--{}--{}--{}--{}'.format(1,2,3,4,5,6,7)
    #1--2--3--4--5--6--7
)
 
# Populate with key fields 
print(
    'I\'m {name1}, and I miss u so much, {name2}.'.format(name1='vergil',name2='hilary')
    #I'm vergil, and I miss u so much, hilary.
)
 
# Fill with subscripts 
names=['hilary','vergil','nero']
places=['chengdu','shijiazhuang','tokyo']
print(
    'Hi, {names[0]}. I am {names[1]} and this is {names[2]}.'.format(names=names)
    #Hi, hilary. I am vergil and this is nero.
)
print(
    'Three people:{0[0]}, {0[1]}, {0[2]} from three places:{1[0]}, {1[1]}, {1[2]}.'.format(names,places)
    #Three people:hilary, vergil, nero from three places:chengdu, shijiazhuang, tokyo.
)
 
# Binary conversion 
print(
    '{0:b}, {0:o}, {1:d}, {1:x}'.format(256,512)
    #100000000, 400, 512, 200
)
# Comma separated 
print(
    '{:,}'.format(12345678)
    #12,345,678
)
# Floating point number format 
print(
    '{:+12.3f}'.format(3.14159265358979)
    #      +3.142
)
# Align and fill 
print(
    '{:>010}'.format(12), # Right Aligned, Width 10 , fill 0
    '{:0<+12.3f}'.format(-12.34567),# Padding 0 , left-aligned, sign-preserving, width 12 , reservation 3 Decimal 
    '|{:^10}|'.format(3) # Default fill spaces, center alignment, width 10
    #0000000012 -12.34600000 |    3     |
)

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: