Python Basic String Formatting Explanation

  • 2021-11-01 03:49:54
  • OfStack

Table of Contents 1. Foreword 2. Percentage Sign 2.1 Reference by Position 2.2 Reference by Keyword 3. format Mode 3.1 Parameter Data Type 3.2 Reference Mode 3.3 Other Configuration Parameters Formatted 3.4 Format Time

1. Preface

There are two ways to format strings for Python: percent sign and format
The percent method is relatively old, while the format method is relatively advanced, trying to replace the ancient method, which is supported by both at present.

2. Percentage sign

%[(name)][flags][width].[precision]typecode


"""
    (name)       Optional, used to select the specified key
    flags           Optional, the values you can choose from are :
        +        Align to the right; Positive numbers are preceded by just, and negative numbers are preceded by minus signs; 
        -         Left alignment; Positive numbers are preceded by unsigned, and negative numbers are preceded by negative signs; 
         Space      Align to the right; Positive numbers are preceded by spaces and negative numbers are preceded by minus signs; 
        0         Align to the right; Positive numbers are preceded by unsigned, and negative numbers are preceded by negative signs; Use 0 Fill in the blanks 
    width          Optional, occupying width 
    .precision    Optional, the number of digits reserved after the decimal point 
    typecode     Required 
        s Object of the incoming object __str__ Method and formats it to the specified location 
        r Object of the incoming object __repr__ Method and formats it to the specified location 
        c Integer: Converts a number to its unicode The corresponding value, 10 The binary range is  0 <= i <= 1114111 ( py27 Only supports 0-255 ); Character: Adds a character to the specified position 
        o Converts integers to  8   Binary representation and formats it to the specified position 
        x Converts integers to 106 Binary representation and formats it to the specified position 
        d Converts integers, floating-point numbers to  10  Binary representation and formats it to the specified position 
        e Converts integers and floating-point numbers to scientific notation and formats them to the specified location (lowercase) e ) 
        E Converts integers and floating-point numbers to scientific notation and formats them to the specified position (uppercase) E ) 
        f ,   Converts an integer, floating-point number, to a floating-point representation and formats it to the specified position (after the decimal point is reserved by default 6 Bits) 
        F Ibid. 
        g Automatic adjustment converts integers, floating-point numbers to   Floating-point or scientific notation representation (exceeding 6 The number of digits is in scientific notation) and formatted to the specified position (if it is a scientific notation, it is e ;) 
        G Automatic adjustment converts integers, floating-point numbers to   Floating-point or scientific notation representation (exceeding 6 The number of digits is in scientific notation) and formatted to the specified position (if it is a scientific notation, it is E ;) 
        % When formatting flags exist in a string, you need to use the  %% Denote 1 Percent sign 
"""

2.1 Transmission of parameters by position


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding

% s print data type


# You can print numbers ,  List ,  Dictionary 
msg = "i am %s, my hobby is %s" % ("xu", 1)  # i am xu, my hobby is 1
print(msg)
msg = "i am %s, my hobby is %s" % ("xu", [1, 2])  # i am xu, my hobby is [1, 2]
print(msg)
msg = "i am %s, my hobby is %s" % ("xu", {"a": "a"})  # i am xu, my hobby is {'a': 'a'}
print(msg)

Print floating-point numbers


f = "percent %.2f" % 99.123456789
print(f)  # percent 99.12

Print with percent sign,%%


f = "percent %.2f%%" % 99.123456789
print(f)  # percent 99.12%

2.2 Transmitting parameters by keywords


msg = "i am %(name)s age %(age)d" % {"name": "xu", "age": 18}
print(msg)  # i an xu age 18

flags and width

flags: Align

width: Occupied width


#  Right alignment 
msg = "i am %(name)+10s age %(age)d" % {"name": "xu" , "age": 18}
print(msg)  # i am         xu age 18
#  Left alignment 
msg = "i am %(name)-10s age %(age)d" % {"name": "xu" , "age": 18}
print(msg)  # i am xu         age 18

3. format mode

[[fill]align][sign][#][0][width][,][.precision][type]


"""
    fill           【可选】空白处填充的字符
    align        【可选】对齐方式(需配合width使用)
        <,内容左对齐
        >,内容右对齐(默认)
        =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
        ^,内容居中
    sign         【可选】有无符号数字
        +,正号加正,负号加负;
         -,正号不变,负号加负;
        空格 ,正号空格,负号加负;
    #            【可选】对于2进制、8进制、106进制,如果加上#,会显示 0b/0o/0x,否则不显示
    ,            【可选】为数字添加分隔符,如:1,000,000
    width       【可选】格式化位所占宽度
    .precision 【可选】小数位保留精度
    type         【可选】格式化类型
        传入” 字符串类型 “的参数
            s,格式化字符串类型数据
            空白,未指定类型,则默认是None,同s
        传入“ 整数类型 ”的参数
            b,将10进制整数自动转换成2进制表示然后格式化
            c,将10进制整数自动转换为其对应的unicode字符
            d,10进制整数
            o,将10进制整数自动转换成8进制表示然后格式化;
            x,将10进制整数自动转换成16进制表示然后格式化(小写x)
            X,将10进制整数自动转换成16进制表示然后格式化(大写X)
        传入“ 浮点型或小数类型 ”的参数
            e, 转换为科学计数法(小写e)表示,然后格式化;
            E, 转换为科学计数法(大写E)表示,然后格式化;
            f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
            F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
            g, 自动在e和f中切换
            G, 自动在E和F中切换
            %,显示百分比(默认显示小数点后6位)
"""

3.1 Parameter data types

Form of key=value


f = "i am {name}, age {age}"
fs = f.format(name="xu", age=18)
print(fs)  # i am xu, age 18

Form of list


f = "i am {:s}, age {:d}"
fs = f.format(*["xu", 19])
print(fs)  # i am xu, age 19

The form of a dictionary


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding
0

Print with different data types


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding
1

3.2 Ways of Transmitting Parameters

Pass parameters by position (default)


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding
2

Pass parameters according to position (specify position parameters)


f = "i am {0}, age {1}, really {0}"
fs = f.format("xu", 12)
print(fs)  # i am xu, age 12, really xu

Transmit parameters according to keywords


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding
4

By parameter attribute


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding
5

Elements through attributes


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding
6

3.3 Additional configuration parameters for formatting

Parameter printing format, taking keyword parameter transmission as an example


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding
7

Add numeric separator and keep 2 decimal places


f = "number: {count:,.2f}"
fs = f.format(count=2123123123)
print(fs)  # number: 2,123,123,123.00

Setting padding characters and alignment


msg = "i am %s, my hobby is %s" % ("xu", 'conding')
print(msg)  # i am xu, my hobby is conding
9

Percent sign


f = "Correct answers:{:.2%}".format(19/22)
print(f)  # Correct answers:86.36%

Formatting data in different binary systems


f = "int: {0:d}, hex:{0:x}, oct:{0:o}, bin:{0:b}"
fs = f.format(42)
print(fs)  # int: 42, hex:2a, oct:52, bin:101010
f = "int: {0:#d}, hex:{0:#x}, oct:{0:#o}, bin:{0:#b}"
fs = f.format(42)
print(fs)  # int: 42, hex:0x2a, oct:0o52, bin:0b101010

3.4 Format Time


import datetime
d = datetime.datetime(2021, 3, 29, 12, 27, 30)
f = "{:%Y-%m-%d %H:%M:%S}"
print(f.format(d))  # 2021-03-29 12:27:30

Related articles: