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}, 年龄 {year}".format(name="xiaoming", year=18))

# 通过字典设置参数
site = {"name": "xiaoming", "year": 18}
print("网站名:{name}, 地址 {url}".format(**site))

# 通过列表索引设置参数
my_list = ['xiaoming',18]
print("姓名:{0[0]}, 年龄 {0[1]}".format(my_list))  # "0" 是可选的

字符格式化

>>> print("{:.4}".format(3.1415926)) 
3.142

format中有丰富的格式限定符,有很多格式限定的方法:

1.填充与对齐

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

>>> print("{:>7}".format(12))
     12
>>> print("{:0>7}".format(12))
0000012
>>> print("{:a>7}".format(12))
aaaaa12

2.精度与类型

>>> print("{:.2f}".format(3.1415926))
3.14

下表展示了 str.format() 格式化数字的多种方法:

数字 格式 输出 描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法

 

 

 

 

 

 

 

 

3.其他类型

主要就是进制,b、d、o、x分别是二进制、十进制、八进制、十六进制

'{:b}'.format(11): 1011  
'{:d}'.format(11): 11
'{:o}'.format(11): 13
'{:x}'.format(11): b
'{:#x}'.format(11): 0xb
'{:#X}'.format(11): 0XB
原文地址:https://www.cnblogs.com/herui1991/p/10569551.html