python——格式化输出、占位符、format()

占位符

常用占位符 描述
%s 字符串
%d 十进制整数
%o 八进制
%x 十六进制
%f 浮点数
>>> 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
>>> print('%d元' % 10)
10元
>>> print('%f' % 1.11)  # 默认保留6位小数
1.110000
>>> print('%.1f' % 1.11)  # 取1位小数
1.1

format()

相对基本格式化输出采用‘%’的方法,format()功能更强大。

>>> 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

猜你喜欢

转载自www.cnblogs.com/lalalaxpf/p/9500853.html