Home >Backend Development >Python Tutorial >How to format output in python
Use % formatted output:
Integer output:
%o —— oct octal
%d —— dec decimal
%x —— hex hexadecimal
>>> print('%o' % 20) 24 >>> print('%d' % 20) 20 >>> print('%x' % 20) 14
Floating point output:
%f ——Retain six significant digits after the decimal point, %.3f, retain 3 decimal places Digits
%e - Retain six significant digits after the decimal point, output in exponential form, %.3e, retain 3 decimal places, use scientific notation
%g - Under the premise of ensuring six significant digits , use decimal mode, otherwise use scientific notation, %.3g, retain 3 significant digits, use decimal or scientific notation
>>> print('%f' % 1.11) # 默认保留6位小数 1.110000 >>> print('%.1f' % 1.11) # 取1位小数 1.1 >>> print('%e' % 1.11) # 默认6位小数,用科学计数法 1.110000e+00 >>> print('%.3e' % 1.11) # 取3位小数,用科学计数法 1.110e+00 >>> print('%g' % 1111.1111) # 默认6位有效数字 1111.11 >>> print('%.7g' % 1111.1111) # 取7位有效数字 1111.111 >>> print('%.2g' % 1111.1111) # 取2位有效数字,自动转换为科学计数法 1.1e+03
String output:
%s
s——right-aligned, placeholder 10 digits
%-10s——left-justified, placeholder 10 digits
%.2s——interception of 2-digit string
.2s— —10-digit placeholder, intercept two-digit string
>>> print('%s' % 'hello world') # 字符串输出 hello world >>> print('%20s' % 'hello world') # 右对齐,取20位,不够则补位 hello world >>> print('%-20s' % 'hello world') # 左对齐,取20位,不够则补位 hello world >>> print('%.2s' % 'hello world') # 取2位 he >>> print('%10.2s' % 'hello world') # 右对齐,取2位 he >>> print('%-10.2s' % 'hello world') # 左对齐,取2位 he
Use the format function
Compared with the basic formatted output using the '%' method, the format() function is more powerful. This function The string is treated as a template, formatted through the passed parameters, and curly brackets '{}' are used as special characters instead of '%'
1, without number, that is, "{}"
2. With numeric numbers, the order can be changed, that is, "{1}", "{2}"
3. With keywords, that is, "{a}", "{tom}"
>>> print('{} {}'.format('hello','world')) # 不带字段 hello world >>> print('{0} {1}'.format('hello','world')) # 带数字编号 hello world >>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序 hello world hello >>> print('{1} {1} {0}'.format('hello','world')) world world hello >>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字 world hello world
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to format output in python. For more information, please follow other related articles on the PHP Chinese website!