Python format 格式化函数 增强了字符串格式化的功能

Python format 格式化函数


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="m.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟", "url": "m.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

输出结果为:

网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com

也可以向 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

format(self=self):

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

上面的 This guy is {self.name},is {self.age} old’.format(self=self)
self包含了name和age的属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值