A detailed description of formatting the format () method in Python
The format output string in Python uses the format () function, the string is the class, you can use the method;
Python is a fully object-oriented language, and everything is an object;
The parameters of the string are represented by {NUM}, 0, representing the first parameter, 1, representing the second parameter, and then sequentially sliding scale;
Use ":" To specify the actions required to represent the element, such as ":. 3", three decimal Places, ": 8" for 8 character spaces, etc.;
You can also add specific letters, such as:
- ' B '-binary. The number is output as a base of 2.
- ' C '-character. Converts an integer to the corresponding Unicode string before printing.
- ' d '-decimal integer. The number is output as a base of 10.
- ' O '-eight binary. The number is output as a base of 8.
- ' x '-16 binary. The number is output in 16, and the number of digits above 9 is in lowercase letters.
- The ' e '-power symbol. Use scientific notation to print numbers, and ' e ' for power.
- ' G '-general format. The value is output in fixed-point format. When the number is particularly large, it is printed in a power form.
- ' N '-number. When the value is an integer and ' d ', the values are the same as the ' G ' when they are floating-point numbers. The difference is that it inserts a numeric delimiter according to the locale.
- '% '-hundred fractions. Multiply the value by 100 and then print in fixed-point (' F ') format, followed by a percent semicolon.
Number (0, 1, ...) Represents the elements inside the format (), so you can use the "." Method of invoking the element;
See URL: http://www.python.org/dev/peps/pep-3101/
The code is as follows:
1 #-*-coding:utf-8-*-2 3Age = 254Name ='Caroline'5 6 Print('{0} is {1} years.'. Format (name, age))#Output Parameters7 Print('{0} is a girl.'. Format (name))8 Print('{0:.3} is a decimal.'. Format (1/3))#three digits after the decimal point9 Print('{0:_^11} is a one-length.'. Format (name))#use _ to empty the spaceTen Print('{First} is as {second}.'. Format (First=name, second='Wendy'))#alias Substitution One Print('My name is {0.name}'. Format (Open ('OUT.txt','W')))#Calling Methods A Print('My name is {0:8}.'. Format ('Fred'))#Specify width
Output:
1 is years old. 2 is a girl. 3 is a decimal. 4 is a one -length . 5 is As Wendy. 6 is 7 is Fred .
Original link: http://blog.csdn.net/caroline_wendy/article/details/17111451
A detailed description of formatting the format () method in Python