码迷,mamicode.com
首页 > 编程语言 > 详细

Python format 格式化函数

时间:2019-03-20 18:50:24      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:comment   class   clear   art   mod   str   follow   view   body   

Python format 格式化函数

函数 str.format(),增强了字符串格式化的功能。 
基本语法是通过 {} 和 : 来代替以前的 % 。 
format 函数可以接受不限个数参数,位置可以不按顺序。 
实例:

>>>"{} {}".format("hello", "world")        # 不设置指定位置,按默认顺序‘hello world‘
>>> "{0} {1}".format("hello", "world")     # 设置指定位置‘hello world‘ 
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置‘world hello world‘
  • 1
  • 2
  • 3
  • 4

也可以设置参数: 
实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = [‘菜鸟教程‘, ‘www.runoob.com‘]print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))# "0" 是可选的
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

输出结果为:

网站名:菜鸟教程,地址 www.runoob.com
网站名:菜鸟教程,地址 www.runoob.com
网站名:菜鸟教程,地址 www.runoob.com
  • 1
  • 2
  • 3

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-
classAssignValue(object):
     def__init__(self, value):
          self.value = valuemy_value = AssignValue(6)
print(‘value 为: {0.value}‘.format(my_value))# "0" 是可选的
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

输出结果为: 
value 为:6

数字格式化

下表展示了 str.format() 格式化数字的多种方法: 
>>>print("{:.2f}".format(3.1415926));3.14

数字格式输出描述
1 3.1415926 {:.2f} 3.14
2 3.1415926 {:+.2f} +3.14
3 -1 {:+.2f} -1.00
4 2.71828 {:.0f} 3
5 5 {:0>2d} 05
6 5 {:x<4d} 5xxx
7 10 {:x<4d} 10xx
8 1000000 {:,} 1,000,000
9 0.25 {:.2%} 25.00%
10 1000000000 {:.2e} 1.00e+09
11 13 {:10d} 13
12 13 {:<10d} 13
13 13 {:^10d} 13
14 11 ‘{:b}‘.format(11) 10
    ‘{:d}‘.format(11) 11
    ‘{:o}‘.format(11) 13
    ‘{:x}‘.format(11) b
    ‘{:#x}‘.format(11) 0xb
    ‘{:#X}‘.format(11) 0XB

此外我们可以使用大括号 {} 来转义大括号,如下实例: 
实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
print("{} 对应的位置是 {{0}}".format("runoob"))
  • 1
  • 2
  • 3

输出结果为:

runoob 对应的位置是{0}

Python format 格式化函数

标签:comment   class   clear   art   mod   str   follow   view   body   

原文地址:https://www.cnblogs.com/zpaixx/p/10566649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!