转于: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. SQLServer将一个表内指定列的所有值插入另一个表

    insert into records_resolve_bak(resolve_save_addr,resolve_time,resolve_status) select  resolve_save_ ...

  2. [转]How Hash Algorithms Work

    来看看SHA-1到底是如何工作的 http://www.metamorphosite.com/one-way-hash-encryption-sha1-data-software

  3. Django APP之contenttypes简单应用

    Conttenttypes介绍 当你看到contenttype你是不是想到了请求头的contenttype? 但是 此contenttypes不是请求头Content-Type而是Django自带的a ...

  4. SMARTFORMS自定义打印格式

    [转自 http://lz357502668.blog.163.com/blog/static/16496743201272155135570/] 在sap的打印开发中经常需要自定义纸张,具体步骤如下 ...

  5. python发布包流程

    1.新建文件夹suba和subb,文件夹下新建__init__.py,内容可以为空 2.suba内新建文件aa.py bb.py 3.subb内新建文件cc.py dd.py 4.setup.py文件 ...

  6. 微信小程序生命周期

    微信小程序 生命周期 通俗的讲,生命周期就是指一个对象的生老病死. 从软件的角度来看,生命周期指程序从创建.到开始.暂停.唤起.停止.卸载的过程. 下面从一下三个方面介绍微信小程序的生命周期: 应用生 ...

  7. Ubuntu12.04等的输入法问题 中英文切换 fitcx

    一般乌班图系统安装的时候会提醒大家选择安装的输入法,若大家选择中文安装,那么支持中文没得说,当选择英文安装的时候,发现整个系统环境是英文,并且根本不能输入中文,想baidu一下都是用pinyin百度, ...

  8. 通过tile和url判断页面跳转是否正确

    通过webdriver中的.title和.current_url获取title和url from time import sleep from selenium import webdriver br ...

  9. python用特殊方法定制类(不全)

    定义在class中不需要直接调用,python的某些函数或操作符会自动的调用对应的特殊方法. 1.python中 __str__和__repr__ __str__()用于显示给用户,而__repr__ ...

  10. python 3 协程函数

    python 3 协程函数 1:把函数的执行结果封装好__iter__和__next__,即得到一个迭代器 2:与return功能类似,都可以返回值,但不同的是,return只能返回一次值,而yiel ...