python中强大的format函数实例详解

作者:hp_cpp 时间:2022-02-19 18:47:10 

python中format函数用于字符串的格式化

自python2.6开始,新增了一种格式化字符串的函数str.format(),此函数可以快速处理各种字符串。

语法

它通过{}和:来代替%。

请看下面的示例,基本上总结了format函数在python的中所有用法


#通过位置
print '{0},{1}'.format('chuhao',20)
print '{},{}'.format('chuhao',20)
print '{1},{0},{1}'.format('chuhao',20)
#通过关键字参数
print '{name},{age}'.format(age=18,name='chuhao')
class Person:
 def __init__(self,name,age):
   self.name = name
   self.age = age
 def __str__(self):
   return 'This guy is {self.name},is {self.age} old'.format(self=self)
print str(Person('chuhao',18))
#通过映射 list
a_list = ['chuhao',20,'china']
print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)
#my name is chuhao,from china,age is 20
#通过映射 dict
b_dict = {'name':'chuhao','age':20,'province':'shanxi'}
print 'my name is {name}, age is {age},from {province}'.format(**b_dict)
#my name is chuhao, age is 20,from shanxi
#填充与对齐
print '{:>8}'.format('189')
#   189
print '{:0>8}'.format('189')
#00000189
print '{:a>8}'.format('189')
#aaaaa189
#精度与类型f
#保留两位小数
print '{:.2f}'.format(321.33345)
#321.33
#用来做金额的千位分隔符
print '{:,}'.format(1234567890)
#1,234,567,890
#其他类型 主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。
print '{:b}'.format(18) #二进制 10010
print '{:d}'.format(18) #十进制 18
print '{:o}'.format(18) #八进制 22
print '{:x}'.format(18) #十六进制12

总结

以上所述是小编给大家介绍的python中强大的format函数实例详解网站的支持!

来源:https://blog.csdn.net/hp_cpp/article/details/84823498

标签:python,format,函数
0
投稿

猜你喜欢

  • ASP 日期的加减运算实现代码

    2011-03-08 10:47:00
  • 解决asp中ADODB.Stream 0x800A0C93 错误

    2008-01-08 19:28:00
  • 关于MySQL编码问题的经验总结

    2007-08-23 16:10:00
  • python 在某.py文件中调用其他.py内的函数的方法

    2021-02-25 23:56:09
  • Python入门教程(三十六)Python的文件写入

    2023-04-30 11:27:48
  • 使用python语言,比较两个字符串是否相同的实例

    2023-08-24 15:01:14
  • pycharm-professional-2020.1下载与激活的教程

    2023-03-08 08:12:38
  • 基于python(urlparse)模板的使用方法总结

    2022-10-08 19:56:50
  • 对Python 语音识别框架详解

    2023-09-22 01:32:30
  • redis查看连接数及php模拟并发创建redis连接的方法

    2023-11-16 11:47:14
  • 在ASP.NET 2.0中操作数据之四十四:DataList和Repeater数据排序(三)

    2023-07-02 04:45:57
  • Python 玩转图像格式转换操作

    2022-03-25 23:14:52
  • Python tkinter实现简单加法计算器代码实例

    2024-01-03 03:58:49
  • python3实现多线程聊天室

    2021-09-11 07:35:47
  • 如何利用Python获取鼠标的实时位置

    2022-08-11 07:00:33
  • 如何利用pytesseract识别图片中的数字

    2023-07-11 12:48:36
  • 如何用Cookie进行登录验证?

    2010-06-12 12:34:00
  • 150行python代码实现贪吃蛇游戏

    2021-07-15 06:43:20
  • python opencv之SIFT算法示例

    2023-12-27 21:42:33
  • 基于python-pptx库中文文档及使用详解

    2023-11-30 12:06:13
  • asp之家 网络编程 m.aspxhome.com