【Python】格式化字符串输出

简介: 一 简介    python 字符串输出格式化有两种方式 %[s,d,] ,python 2.6 版本提供了string.format(),其功能也相当强大。talk is cheap,show me the code .
一 简介
   python 字符串输出格式化有两种方式 %[s,d,] , python 2.6 版本提供了string.format(),其功能也相当强大。talk is cheap,show me the code .
二 使用
2.1 参数映射
str.format 通过 {} 替换 字符串的 %,我们可以使用基于位置映射参数,基于下表,基于参数
比如 

  1. In [23]: print 'i am a %s,work at %s !' %('dba','youzan')
  2. i am a dba,work at youzan !
  3. In [24]: print 'i am a {0},work at {1} !'.format('dba','youzan')
  4. i am a dba,work at youzan !
  5. In [26]: print 'i am a {arg},work at {company} !'.format(arg='dba',company='youzan')
  6. i am a dba,work at youzan !
  7. format 不限制参数的调用次数
  8. In [28]: print 'i am a {0},work at {1},and {1} is  good at SAAS service !'.format('dba','youzan')
  9. i am a dba,work at youzan,and youzan is  good at SAAS service !

2.2 格式化输出
% 提供丰富的格式化输出,format当然也有同样的功能。
填充与对齐 
^ 居中
< 左对齐
> 右对齐 后面带宽度
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
具体的使用方式如下
  1. In [30]: fs='{:<8}'
  2. In [31]: fs.format('dba')
  3. Out[31]: 'dba '
  4. In [32]: fs='{:1<8}'
  5. ##左对齐
  6. In [33]: fs.format('dba')
  7. Out[33]: 'dba11111'
  8. #右对齐
  9. In [34]: fs='{:1>8}'
  10. In [35]: fs.format('dba')
  11. Out[35]: '11111dba'
  12. #居中
  13. In [36]: fs='{:1^8}'
  14. In [37]: fs.format('dba')
  15. Out[37]: '11dba111'
浮点数精度
  1. In [40]: fs='{:.3f}'
  2. In [41]: fs.format(3.14159265358)
  3. Out[41]: '3.142'
数字的进制
  1. b 分别是二进制
  2. d 十进制
  3. o 八进制
  4. x 十六进制。
  1. In [42]: ':b'.format(29)
  2. Out[42]: ':b'
  3. In [43]: '{:b}'.format(29)
  4. Out[43]: '11101'
  5. In [44]: '{:d}'.format(29)
  6. Out[44]: '29'
  7. In [45]: '{:x}'.format(29)
  8. Out[45]: '1d'
  9. In [46]: '{:o}'.format(29)
  10. Out[46]: '35'
用逗号 还能用来做金额的千位分隔符。

  1. In [47]: '{:,}'.format(2132323455)
  2. Out[47]: '2,132,323,455'

三 小结
  理论知识就介绍到这里了,如何在实际中运用呢?就交给给位读者朋友了。
目录
相关文章
|
6月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
399 100
|
6月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
561 99
|
6月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
6月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
6月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
6月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
7月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
416 0
|
7月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。
|
7月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
383 92

推荐镜像

更多