Python format 格式化函数 您所在的位置:网站首页 format函数python作用 Python format 格式化函数

Python format 格式化函数

#Python format 格式化函数| 来源: 网络整理| 查看: 265

Python 字符串 Python 字符串

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

实例 >>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'

也可以设置参数:

实例 #!/usr/bin/python # -*- coding: UTF-8 -*- print("网站名:{name}, 地址 {url}".format(name="小白教程", url="")) # 通过字典设置参数 site = {"name": "小白教程", "url": ""} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['小白教程', ''] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

输出结果为:

网站名:小白教程, 地址 网站名:小白教程, 地址 网站名:小白教程, 地址

也可以向 str.format() 传入对象:

实例 #!/usr/bin/python # -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('value 为: {0.value}'.format(my_value)) # "0" 是可选的

输出结果为:

value 为: 6 数字格式化

下表展示了 str.format() 格式化数字的多种方法:

>>> print("{:.2f}".format(3.1415926)); 3.14 数字格式输出 描述 3.1415926 {:.2f} 3.14 保留小数点后两位 3.1415926 {:+.2f} +3.14 带符号保留小数点后两位 -1 {:+.2f} -1.00 带符号保留小数点后两位 2.71828 {:.0f} 3 不带小数 5 {:0>2d} 05 数字补零 (填充左边, 宽度为2) 5 {:x


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有