转于:https://blog.csdn.net/zhang89xiao/article/details/53818906

博主:张肖的博客

描述:

format的格式

replacement_field     ::=  “{” [field_name] [“!” conversion] [“:” format_spec] “}”
field_name              ::=      arg_name (“.” attribute_name | “[” element_index “]”)*
arg_name               ::=      [identifier | integer]
attribute_name       ::=      identifier
element_index        ::=      integer | index_string
index_string           ::=      <any source character except “]”> +
conversion              ::=      “r” | “s” | “a”
format_spec            ::=      <described in the next section>

format_spec 的格式

format_spec   ::=    [[fill]align][sign][#][0][width][,][.precision][type]

fill             ::=    <any character>
align           ::=    ”<” | “>” | “=” | “^”
sign            ::=    ”+” | “-” | ” “
width           ::=    integer
precision       ::=    integer
type            ::=    ”b” | “c” | “d” | “e” | “E” | “f” | “F” | “g” | “G” | “n” | “o” | “s” | “x” | “X” | “%”

功能:共4个功能

一)填充字符串

#只能用{ }来放标签

A、通过位置填充字符串:{0},表示format的左起第一个元素;

print('hello {0} i am {1}, {1} love {0}'.format('MM', 'GG'))
#输出:hello MM i am GG, GG love MM

B、通过key来填充

print('hello {0} i am {g}, {g} love {0}'.format('MM', g = 'GG'))
#输出:hello MM i am GG, GG love MM

C、通过下标填充

#format的参数,当'I', names = names, u = 'U',三种混用是,'I'类型放最前;

names = ['MM', 'GG']
print('hello {names[0]}, i am {names[1]}, {0} love {u}'.format('I', names = names, u = 'U'))
#输出:hello MM i am GG, I love U

D、通过字典的key填充

names = {'m':'MM', 'g':'GG'}
print('hello {names[m]} i am {names[g]}, {i} love {u}'.format(names = names, i = 'I',u = 'U'))
#输出:hello MM i am GG, I love U

E、通过对象的属性填充

class Names():
m = 'MM'
g = 'GG' print('hello {names.m}, i am {names.g}'.format(names = Names))
#输出:hello MM, i am GG

F、使用魔法参数填充

args = ['I', 'U']
kwargs = {'m':'MM', 'g':'GG'}
print('hello {m} , i am {g}, {} love {}'.format(*args, **kwargs))
#输出:hello MM , i am GG, I love U

二)格式转换

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

方式一:{:条件}.format(参数)

a = 3.14159
b = '{:.2f}'.format(a)
print(b)
#输出:3.14 c = '{:+.2f}'.format(a)
print(c)
#输出:+3.14

方式二:format(参数, '.条件'),不需要{: }

# '+.2f':此处只能是具体数字2,不能是字符变量;

b = format(3.14159, '+.2f')
print(b)
#输出:+3.14
参数 条件的格式 输出 描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} 3.14 带符号保留小数点后两位
-1 {:+.2f} -1 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00E+09 指数记法
25 {0:b} 11001 转换成二进制
25 {0:d} 25 转换成十进制
25 {0:o} 31 转换成八进制
25 {0:x} 19 转换成十六进制

三)字符串对齐于填充

方式一:{:条件}.format(参数)

方式二:format(参数, '.条件'),不需要{: }

# format(参数, '.条件')中,'0>5'中,只能是5,不能是字符变量;

参数 j条件格式 输出 描述
5 {:0>2} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x^4} x10x 数字补x (填充右边, 宽度为4)
13 {:10}         13 右对齐 (默认, 宽度为10)
13 {:<10} 13 左对齐 (宽度为10)
13 {:^10}     13 中间对齐 (宽度为10)

四)其它

A、转义{和}符号

1
print '{{ hello {0} }}'.format('Kevin')

跟%中%%转义%一样,formate中用两个大括号来转义

B、format作为函数

1
2
f = 'hello {0} i am {1}'.format    
print f('Kevin','Tom')

C、格式化datetime

1
2
now=datetime.now()
print '{:%Y-%m-%d %X}'.format(now)

D、{}内嵌{}

1
print 'hello {0:>{1}} '.format('Kevin',50)

E、叹号的用法

# !后面可以加s r a 分别对应str() repr() ascii()

# 作用:在填充前先用对应的函数来处理参数

1
2
print "{!s}".format('2')  # 2
print "{!r}".format('2')   # '2'

差别就是repr带有引号,str()是面向用户的,目的是可读性,repr()是面向python解析器的,返回值表示在python内部的含义

ascii()一直报错,可能这个是3.0才有的函数

Python:format()方法的更多相关文章

  1. python的str.format方法

    format方法被用于字符串的格式化输出. print('{0}+{1}={2}'.format(1,2,1+2)) #in 1+2=3 #out 可见字符串中大括号内的数字分别对应着format的几 ...

  2. Python里format()方法基本使用

    '''第一种:自然连接''' #format 连接字符串 str = '{}使用的python是{}版本'.format('我','3.6.5') print(str) #打印结果:我使用的pytho ...

  3. #python str.format 方法被用于字符串的格式化输出。

    #python str.format 方法被用于字符串的格式化输出. #''.format() print('{0}+{1}={2}'.format(1,2,3)) #1+2=3 可见字符串中大括号内 ...

  4. Python中格式化format()方法详解

    Python中格式化format()方法详解 Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法; Python是完全面向对象的语言, 任何东西都是对象; 字符串的参 ...

  5. Python入门之format()方法

    在此列出format()方法的一些基本使用: >>> '{}{}{}'.format('圆周率是',3.1415926,'...') '圆周率是3.1415926...' >& ...

  6. Python 字符串格式化操作 - format方法

    建议使用format()方法 字符串操作 对于 %, 官方以及给出这种格式化操作已经过时,在 Python 的未来版本中可能会消失. 在新代码中使用新的字符串格式.因此推荐大家使用format()来替 ...

  7. Python字符串类型格式化之format方法

    python字符串格式化一般使用 format() 方法,用法如下: <模板字符串>.format(<逗号分割的参数>) 其中模板字符串中可以由一个或多个 {} 组成的 槽 , ...

  8. python format使用方法

    #使用format 方法进行格式化 print("The number {1:} in hex is: {1:#x}, the number {0:} in oct is {0:o}&quo ...

  9. Python str方法总结

    1.返回第一个字母大写 S.capitalize(...) S.capitalize() -> string 1 2 3 4 >>>a = 'shaw' >>> ...

  10. Python魔法方法总结及注意事项

    1.何为魔法方法: Python中,一定要区分开函数和方法的含义: 1.函数:类外部定义的,跟类没有直接关系的:形式: def func(*argv): 2.方法:class内部定义的函数(对象的方法 ...

随机推荐

  1. Django开发模式会加载两次settings文件导致RotatingFileHandlerError

    当使用RotatingFileHandler作为django的日志处理器的时候,会报: Traceback (most recent call last): File "C:\Python2 ...

  2. [转载]设计模式的UML图

    1.抽象工厂(Abstract Factory)模式 意图:为特定的客户(或情况)提供特定系列的对象. 2.类的适配器(Adapter)模式 意图:将一个类的接口转换成客户希望的另外一个接口. 3.对 ...

  3. SQL性能优化常用语句(摘录网上)

    1.把trace文件导入到表中 , ) AS RowNumber,* into TableName FROM fn_trace_gettable('trace.trc', default) 2.查询C ...

  4. 第2条:遵循PEP8风格指南

    <Python Enhancement Proposal #8>(8号Python增强提案)又叫PEP8,它是针对Python代码格式而编订的风格指南. 尽管可以在保证语法正确的前提下随意 ...

  5. LeetCode:删除排序数组中的重复项||【80】

    LeetCode:删除排序数组中的重复项||[80] 题目描述 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度. 不要使用额外的数组空间,你必须在原 ...

  6. iOS block 闭包的学习

    iOS  闭包 学习 理解: 1 .   闭包外界无法访问内部变量 ,它是一个独立的代码块. 2 .   闭包可以作为 一个方法 ,甚至局部变量  全局 变量 3 .   闭包 是一种引用类型   注 ...

  7. 【LeetCode】:二叉搜索树

    相关概念: 一棵二叉搜索树(BST)是以一棵二叉树来组织的,可以用链表数据结构来表示,其中,每一个结点就是一个对象,一般地,包含数据内容key和指向孩子(也可能是父母)的指针属性.如果某个孩子结点不存 ...

  8. mysql innobackupex备份实施

    最近用innobackup进行备份测试,我们只备份一个innodb类型的库,数据大小大概50多G,用innobackupex大概用了5个多小时,但是mysqldump只用了大约2个小时,这让我很费解, ...

  9. inline-block间距解决方案

    当我们将元素设为inline-block时,总是会莫名其妙出现一些间距 <!DOCTYPE html> <html> <head> <meta charset ...

  10. mysql 索引技巧

    索引是快速搜索的关键.MySQL索引的建立对于MySQL的高效运行是很重要的.下面介绍几种常见的MySQL索引类型. 在数据库表中,对字段建立索引可以大大提高查询速度.假如我们创建了一个 mytabl ...