Python format format of method

  • 2020-05-27 06:25:38
  • OfStack

Python format format() method

Python USES the format() function to format the output string.

Python is a fully object-oriented language. Everything is an object.

The parameters of the string are represented by {NUM},0, which means the first parameter,1, which means the second parameter, and then successively added;

Use ":" to specify the operations required to represent the element, such as ":.3" for 3 decimal places, ":8" for 8 character Spaces, etc.

You can also add specific letters, such as:

'b' - 2. Outputs Numbers to base 2. 'c' - character. Converts the integer to the corresponding Unicode string before printing. 'd' - a decimal integer. Output the number to base 10. 'o' -8. Outputs Numbers in base 8. 'x' -106. Output Numbers in base 16, with digits above 9 in lowercase letters. 'e' - power symbol. Use scientific counting to print Numbers. Use 'e' for power. 'g' -1 format. Output values in fixed-point format. When values are particularly large, print them in power format. 'n' - number. Same as 'd' when it is an integer, same as 'g' when it is a floating point number. The difference is that it inserts a number separator based on the locale. '%' - percent. Multiply the value by 100 and print it in fixed-point ('f') format. The value is followed by a percent sign.

Number (0, 1...) That is, it represents the element inside format(), so you can use "." to call the element's methods;

See url: http: / / www python. org/dev/peps / / pep - 3101

The code is as follows:


# -*- coding: utf-8 -*- 
 
#==================== 
#File: abop.py 
#Author: Wendy 
#Date: 2013-12-03 
#==================== 
 
#eclipse pydev, python3.3 
 
age = 25 
name = 'Caroline' 
 
print('{0} is {1} years old. '.format(name, age)) # Output parameters  
print('{0} is a girl. '.format(name)) 
print('{0:.3} is a decimal. '.format(1/3)) # After the decimal point 3 position  
print('{0:_^11} is a 11 length. '.format(name)) # use _ Swallow the vacancy  
print('{first} is as {second}. '.format(first=name, second='Wendy')) # The alias substitution  
print('My name is {0.name}'.format(open('out.txt', 'w'))) # A method is called  
print('My name is {0:8}.'.format('Fred')) # Specifies the width of the  

Output:


Caroline is 25 years old.  
Caroline is a girl.  
0.333 is a decimal.  
_Caroline__ is a 11 length.  
Caroline is as Wendy.  
My name is out.txt 
My name is Fred  . 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: