python string formatting --format

Basic usage:
>>>"my name is {} and I am {} years old".format("junex",18)
>>>'my name is junex and I am 18 years old'

"{}" is equivalent to a placeholder, and then format() is called to assign a value. What if you want to use format() and also want to output "{}"?

>>>"hello {} and {{}}".format("world")
>>>'hello world and {}'
parameter rearrangement

You can use the form of "{index}" to correspond to the parameters of format(param0,param1,...), note that the index should start from 0:

>>>"apple is {0}, banana is {1}".format("red","yellow")
>>>'apple is red, banana is yellow'

>>>"apple is {1}, banana is {0}".format("red","yellow")
>>>'apple is yellow, banana is red'

You can also use "{parameter name}" to correspond to parameters. The advantage of this is that the code is easier to read and you don't need to care about the order of parameters:

>>>"my name is {name} and I am {age} years old".format(age=18,name="junex")
>>>'my name is junex and I am 18 years old'
Specify the variable type

At this time, it is more advanced, you need to use the syntax of {field_name:conversion} , field_name is to indicate the corresponding relationship between {} and parameters, and conversion is used to format the string.

#指明数据类型为浮点数
>>>"Today's temperature is {:f} degrees Celsius".format(12)
>>>'Today's temperature is 12.000000 degrees Celsius'

#规定浮点数的精确度
>>>"Today's temperature is {:.3f} degrees Celsius".format(12)
>>>'Today's temperature is 12.000 degrees Celsius'

For more usage, see the official documentation

filling

You can use a : (colon) followed by a number to indicate the space occupied by the parameter.

>>>"my name is {:20} and I am {:8} years old".format("junex", 18)
>>>"my name is junex                     and I am         18 years old".format("junex", 18)

You can see that strings are left-aligned by default, and numbers are right-aligned by default.

#左对齐
>>>"{:<10}".format("junex")
>>>'     junex'
#居中
>>>"{:^10}".format("junex")
>>>'  junex   '
#右对齐
>>>"{:>10}".format("junex")
>>>'junex     '

As you can see, python uses spaces to pad by default, and we can also use custom characters to pad:

>>>"{:*^10}".format("junex")
>>>'**junex***'   

I encountered a problem during use:
write picture description here
miao
the reason is that when padding with 0, '=' will be used by default, while '=' can only be used for numbers. Because '9' is a string, the above error will be reported.
The locator can be used to solve the problem:
999

Refer How To Use String Formatters in Python 3 & Official Documentation

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325518769&siteId=291194637