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

三 小结
  理论知识就介绍到这里了,如何在实际中运用呢?就交给给位读者朋友了。
目录
相关文章
|
11天前
|
Python
1167: 分离字符串(PYTHON)
1167: 分离字符串(PYTHON)
|
29天前
|
大数据 Python
使用Python查找字符串中包含的多个元素
本文介绍了Python中查找字符串子串的方法,从基础的`in`关键字到使用循环和条件判断处理多个子串,再到利用正则表达式`re模块`进行复杂模式匹配。文中通过实例展示了如何提取用户信息字符串中的用户名、邮箱和电话号码,并提出了优化策略,如预编译正则表达式和使用生成器处理大数据。
20 1
|
1月前
|
数据挖掘 开发者 Python
Python:字符串判断子串
Python:字符串判断子串
|
1月前
|
程序员 数据安全/隐私保护 Python
Python:翻转字符串
Python:翻转字符串
|
1月前
|
Python
利用Python生成字符串连接
利用Python生成字符串连接
19 0
|
1月前
|
索引 Python
Python系列(14)—— 字符串运算符
Python系列(14)—— 字符串运算符
|
1月前
|
存储 自然语言处理 数据挖掘
Python:计算字符串中每个单词出现的次数
Python:计算字符串中每个单词出现的次数
|
3天前
|
数据采集 Python
python学习9-字符串
python学习9-字符串
|
11天前
|
Python
171: 字符串的倒序(python)
171: 字符串的倒序(python)
|
28天前
|
JSON C++ 数据格式
【Python 基础教程 08】全面入门到精通:Python3 字符串操作实战教程与深度指南
【Python 基础教程 08】全面入门到精通:Python3 字符串操作实战教程与深度指南
85 0

热门文章

最新文章