Python basic formatted output

What is formatted output?

The data is output according to some special requirements

If you input an integer, you want the integer to be output in hexadecimal or octal. If you input a decimal, you want the decimal to retain the last 2 digits and then output, or output the decimal in scientific notation. The output of the string is expected to be output within ten grids, or left-aligned, centered, etc.

Python string formatting symbols:

1.png


#Formatted  output about integers

num01 , num02 = 200 , 300

print ( " Octal output: 0o%o,0o%o" % ( num01 , num02))

print ( " hexadecimal output: 0x%x,0x%x" % ( num01 , num02))

print ( " Decimal output: %d,%d" % ( num01 , num02))

print ( "binary output of 200 : " , bin ( num01 ) , "binary output of 300 is: " , bin (num02))

2.png


#float  output

%f retains six significant digits after the decimal point, %.3f retains three decimal places

%e retains six significant digits after the decimal point, and outputs in exponential form. %.3e keep 3 decimal places, use scientific notation

%g Use decimal notation under the premise of retaining six significant figures, otherwise scientific notation is used. %3g keep 3 significant digits, use decimal or scientific notation

 

num01 = 123456.8912

print ( " Standard pattern: %f" % num01 )

print ( " Retain two significant digits: %.2f" % num01 )

print ( " Standard mode for e: %e" % num01 )

print("e的留两位有效数字:%.2e"%num01)

print("g的标准模式:%g"%num01) #如果是7位保留不了就用科学计数法表示

print("g的留两位有效数字:%.2g"%num01)

3.png


#字符串的格式化输出

%s 标准输出

%10s 右对齐,占位符10位

%10s 左对齐,占位符10位

%.2s 截取2位字符串

%10.2s 10位占位符,截取两位字符串

 

str01="www.iLync.cn"

print("s标准输出:%s"%str01)

print ( " Fixed space output of s: %20s" % str01 ) # right justified

print ( "s fixed space output: %-20s" % str01 ) #left justified

print ( "s interception: %.3s" % str01 ) # intercept the first three characters

print ( "s interception: %10.3s" % str01 )

print ( "s interception: %-10.3s" % str01 )

4.png


Guess you like

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