应用%格局化输入:
整数输入:
%o —— oct 八进制
%d —— dec 十进制
%x —— hex 十六进制
>>> print('%o' % 20) 24 >>> print('%d' % 20) 20 >>> print('%x' % 20) 14
浮点数输入:
%f ——保存小数点前面六位无效数字,%.3f,保存3位小数位
%e ——保存小数点前面六位无效数字,指数方式输入,%.3e,保存3位小数位,应用迷信计数法
%g ——正在保障六位无效数字的条件下,应用小数形式,不然应用迷信计数法,%.3g,保存3位无效数字,应用小数或迷信计数法
>>> 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
字符串输入:
%s
%10s——右对齐,占位符10位
%-10s——左对齐,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取两位字符串
>>> 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
应用format函数
绝对根本格局化输入采纳‘%’的办法,format()性能更弱小,该函数把字符串当成一个模板,经过传入的参数进行格局化,而且应用年夜括号‘{}’作为非凡字符替代‘%’
一、没有带编号,即“{}”
二、带数字编号,可互换程序,即“{1}”、“{2}”
三、带要害字,即“{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
更多Python相干技巧文章,请拜访Python教程栏目进行学习!
以上就是python怎样格局化输入的具体内容,更多请存眷资源魔其它相干文章!
标签: python教程 python编程 python使用问题 python怎么格式化输出
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!