鱼C论坛

 找回密码
 立即注册
查看: 2263|回复: 0

[技术交流] python学习笔记9 格式化format

[复制链接]
发表于 2017-6-20 22:06:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
格式化字符串的format函数介绍,在python中,用此函数便可轻松格式化任意字符串。

  1. #(0)
  2. print('(0)')
  3. age = 27
  4. name = 'bob'

  5. print('{0} is a {1} years old man , and now he is strating stduy python.'.format(name,age))
  6. print('he is {} years old'.format(age))


  7. #(1)
  8. print('(1)')
  9. # 对于浮点数 '0.333' 保留小数点(.)后三位
  10. print('{0:.3f}'.format(1.0/3))
  11. # 使用下划线填充文本,并保持文字处于中间位置
  12. # 使用 (^) 定义 '___hello___'字符串长度为 11
  13. print('{0:_^11}'.format('hello'))
  14. # 基于关键词输出 'Swaroop wrote A Byte of Python'
  15. print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))
复制代码



输出结果为
  1. (0)
  2. bob is a 27 years old man , and now he is strating stduy python.
  3. he is 27 years old
  4. (1)
  5. 0.333
  6. ___hello___
  7. Swaroop wrote A Byte of Python
复制代码


评分

参与人数 1鱼币 +1 收起 理由
小甲鱼 + 1 支持楼主!

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 18:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表