zoukankan      html  css  js  c++  java
  • python 格式化输出(% VS format)

    提到Python中的格式化输出方法,一般来说有以下两种方式:

    1)%

    格式说明由%和格式字符组成,如%f,%s,%d,它的作用是将数据按照指定的格式输出。格式说明是由“%”字符开始的。

     1 #1.输出字符串%s
     2 print('my name is %s' % ('xiaoming'))
     3 
     4 #2.整型输出%d
     5 print('My sister is %s, Her age is %d,'%('Lina',18))
     6 
     7 #3.输出浮点数
     8 print('Her height is %f m' % (1.6500))
     9 
    10 #4.保留2位小数
    11 print('His height is %.2f m' % (1.6500))
    12 
    13 #5.指定占位符宽度
    14 print('name:%10s  age:%10d height:%5.2f' % ('Lina',18,1.6500))
    15 
    16 #6.指定占位符宽度(左对齐)
    17 print('name:%-10s  age:%-10d  height:%-5.2f' % ('Lina',18,1.6500))
    18 
    19 #7.字符串截取
    20 print('%.5s' % ('hello word'))#截取前5个字符
    21 
    22 '''
    23 运行结果
    24 my name is xiaoming
    25 My sister is Lina, Her age is 18,
    26 Her height is 1.650000 m
    27 His height is 1.65 m
    28 name:      Lina  age:        18 height: 1.65
    29 name:Lina        age:18          height:1.65 
    30 hello
    31 
    32 
    33 '''
    View Code

    2) format

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

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

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

    基本用法

     1 print('{} {}'.format('hello', 'world'))  # 最基本的
     2 
     3 print('{0} {1}'.format('hello', 'world'))  # 通过位置参数
     4 
     5 print('{0} {1} {0}'.format('hello', 'world'))  # 单个参数多次输出
     6 
     7 """输出结果
     8 hello world
     9 hello world
    10 hello world hello
    11 """
    View Code

    关键词定位

     1 # 通过关键词参数
     2 print('我的名字是{name},我今年{age}岁了。'.format(name='Linda', age='18'))
     3 
     4 # 与位置参数一样,单个参数也能多次输出
     5 print('{name}说:"我的名字是{name},我今年{age}岁了。"'.format(name='linda', age='18'))
     6 
     7 """输出结果
     8 我的名字是linda,我今年18岁了。
     9 linda说:"我的名字是Linda,我今年18岁了。"
    10 """
    View Code

    可变参数

    可传入list、dic类型

     1 # 传入list
     2 data = ['hello', 'world']
     3 print('{0} {1}'.format(*data))
     4 
     5 # 传入dict
     6 data = {'name': '小明', 'age': 12}
     7 print('我的名字是{name},我今年{age}岁了。'.format(**data))
     8 
     9 # 混用
    10 data_1 = ['hello', 'world']
    11 data_2 = {'name': '小明', 'age': 12}
    12 print('{0} {1} 我的名字是{name},我今年{age}岁了,{0}!'.format(*data_1, **data_2))
    13 
    14 """输出结果
    15 hello world
    16 我的名字是小明,我今年12岁了。
    17 hello world 我的名字是小明,我今年12岁了,hello!
    18 """
    View Code

    固定宽度

    format()可以指定输出宽度为多少,当字符串长度少于设定值的时候,默认用空格填充:

     1 data = [{'name': 'Mary', 'college': 'Tsinghua University'},
     2         {'name': 'Micheal', 'college': 'Harvard University'},
     3         {'name': 'James', 'college': 'Massachusetts Institute of Technology'}]
     4 # 固定宽度输出
     5 for item in data:
     6     print('{:10}{:40}'.format(item['name'], item['college']))
     7 
     8 """输出结果
     9 Mary      Tsinghua University                     
    10 Micheal   Harvard University                      
    11 James     Massachusetts Institute of Technology   
    View Code

    当然除了空格,我们也可以选择其他字符来填充,譬如我想打印一条分割线,便可以选择通过-来填充:

     1 data = [{'name': 'Mary', 'college': 'Tsinghua University'},
     2         {'name': 'Micheal', 'college': 'Harvard University'},
     3         {'name': 'James', 'college': 'Massachusetts Institute of Technology'}]
     4 
     5 # 固定宽度输出
     6 for item in data:
     7     # 每输出一条记录之前打印一条分割线
     8     # 选择用其他字符来填充时需要指定对齐方式
     9     print('{:-^60}'.format('我是分割线'))
    10     print('{:10}{:40}'.format(item['name'], item['college']))
    11 
    12 """输出结果
    13 ---------------------------我是分割线----------------------------
    14 Mary      Tsinghua University                     
    15 ---------------------------我是分割线----------------------------
    16 Micheal   Harvard University                      
    17 ---------------------------我是分割线----------------------------
    18 James     Massachusetts Institute of Technology   
    19 """
    View Code

    对齐方式

    format()支持左对齐,右对齐,居中,分别对应<>^,具体怎么使用我们看实例:

     1 data = [{'name': 'Mary', 'college': 'Tsinghua University'},
     2         {'name': 'Micheal', 'college': 'Harvard University'},
     3         {'name': 'James', 'college': 'Massachusetts Institute of Technology'}]
     4 
     5 
     6 print('{:-^50}'.format('居中'))
     7 for item in data:
     8     print('{:^10}{:^40}'.format(item['name'], item['college']))
     9 
    10 print('{:-^50}'.format('左对齐'))
    11 for item in data:
    12     print('{:<10}{:<40}'.format(item['name'], item['college']))
    13 
    14 print('{:-^50}'.format('右对齐'))
    15 for item in data:
    16     print('{:>10}{:>40}'.format(item['name'], item['college']))
    17 
    18 """输出结果
    19 ------------------------居中------------------------
    20    Mary             Tsinghua University           
    21  Micheal             Harvard University           
    22   James    Massachusetts Institute of Technology  
    23 -----------------------左对齐------------------------
    24 Mary      Tsinghua University                     
    25 Micheal   Harvard University                      
    26 James     Massachusetts Institute of Technology   
    27 -----------------------右对齐------------------------
    28       Mary                     Tsinghua University
    29    Micheal                      Harvard University
    30      James   Massachusetts Institute of Technology
    31 """
    View Code

    数字格式化

    常用的示例如下:

     1 # 取小数点后两位
     2 num = 3.1415926
     3 print('小数点后两位:{:.2f}'.format(num))
     4 
     5 # 带+/-输出
     6 num = -3.1415926
     7 print('带正/负符号:{:+.2f}'.format(num))
     8 
     9 # 转为百分比
    10 num = 0.34534
    11 print('百分比:{:.2%}'.format(num))
    12 
    13 # 科学计数法
    14 num = 12305800000
    15 print('科学计数法:{:.2e}'.format(num))
    16 
    17 # ,分隔
    18 num = 12305800000
    19 print('","分隔:{:,}'.format(num))
    20 
    21 # 转为二进制
    22 num = 15
    23 print('二进制:{:b}'.format(num))
    24 
    25 # 十六进制
    26 num = 15
    27 print('十六进制:{:x}'.format(num))
    28 
    29 # 八进制
    30 num = 15
    31 print('八进制:{:o}'.format(num))
    32 
    33 """输出结果
    34 小数点后两位:3.14
    35 带正/负符号:-3.14
    36 百分比:34.53%
    37 科学计数法:1.23e+10
    38 ","分隔:12,305,800,000
    39 二进制:1111
    40 十六进制:f
    41 八进制:17
    42 """
    View Code

     

    可以设置参数

     1 print("网站名:{name}, 地址 {url}".format(name="博客园", url="https://home.cnblogs.com/u/yaner2018/"))
     2  
     3 # 通过字典设置参数
     4 site = {"name": "博客园", "url": "www.runoob.com"}
     5 print("网站名:{name}, 地址 {url}".format(**site))
     6  
     7 # 通过列表索引设置参数
     8 my_list = ['博客园', 'https://home.cnblogs.com/u/yaner2018/']
     9 print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
    10 
    11 '''
    12 网站名:博客园, 地址 https://home.cnblogs.com/u/yaner2018/
    13 网站名:博客园, 地址 https://home.cnblogs.com/u/yaner2018/
    14 网站名:博客园, 地址 https://home.cnblogs.com/u/yaner2018/
    15 '''
    View Code

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

    1 class demo(object):
    2     def __init__(self, value):
    3         self.value = value
    4 my_value = demo(6)
    5 print('value 为: {0.value}'.format(my_value))  # "0" 是可选的
    View Code

    -----------------------------------------总结-----------------------------------------------------

    ^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

    + 表示在正数前显示 +,负数前显示 -;  (空格)表示在正数前加空格

    b、d、o、x 分别是二进制、十进制、八进制、十六进制。

    ------------------------------------------------------------------------------------------------

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

    print ("{} 对应的位置是 {{0}}".format("runoob"))

    #输出:

    #runoob 对应的位置是 {0}

  • 相关阅读:
    《自我介绍》
    《结对-结对编项目作业名称-开发环境搭建过程》
    提取图形中指定颜色的所有像素_opencv/c++
    图形锐化_opencv/C++
    Opencv2.4.13 与Visual Studio2013 环境搭建配置
    C++基础——C面向过程与C++面向对象编程01_圆面积求解
    2017年2月26日
    基于GDAL的遥感影像显示(C#版)
    GDAL C# 开发环境配置
    shp文件的读取
  • 原文地址:https://www.cnblogs.com/yaner2018/p/11769801.html
Copyright © 2011-2022 走看看