Blogger Information
Blog 75
fans 0
comment 0
visits 54651
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
小猿圈python之python格式化
聆听的博客
Original
1094 people have browsed it

格式化在哪门语言都会用到,今天小猿圈讲师说一下python的格式化,正在学习python的朋友们可以看一下,或者对这个有点疑惑可以学习一下,解决你的疑惑,下面咱们具体讲解一下python的格式化内容。

一、格式化输出

1、整数的输出

%o —— oct 八进制

%d —— dec 十进制

%x —— hex 十六进制

实例

>>> print('%o' % 20)

24

>>> print('%d' % 20)

20

>>> print('%x' % 20)

14

运行实例 »

点击 "运行实例" 按钮查看在线实例

2、浮点数输出

%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

运行实例 »

点击 "运行实例" 按钮查看在线实例

3、字符串输出

%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

运行实例 »

点击 "运行实例" 按钮查看在线实例

目前python就这两种格式化:%和.format,这篇小编只说了一下%,大家把之前的疑惑解开了吗?或者真正理解了吗?学会了小编的目的也就达到了,下一篇小编讲解一下format()方法格式化,感兴趣的朋友可以去小猿圈先预习一下,然后看一下小编的下一篇文章。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!