目录
str.format()用法说明
格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过{} 和 :
来代替以前的 % 。【真的巨巨巨方便】
代码示例
str.format()可以接受不限个参数,位置可以不按顺序。
print("{} {}".format("hello", "world")) #不设置指定位置,按默认顺序
print("{0} {1}".format("hello", "world")) #设置指定位置
print( "{1} {0} {1}".format("hello", "world")) # 设置指定位置
str.format()可以设置参数、通过字典设置参数、通过列表索引设置参数
print('{0},{1}'.format('xpt', 18))
print('{},{},{}'.format('xpt', 'fm', 18))
#可以设置参数
print('{name},{sex},{age}'.format(age=18, sex='fm', name='xpt'))
# 通过字典设置参数
site = {'name': 'xpt', 'url': 'https://xxpt.github.io/xxpt.github.io/'} # 字典dict格式 {'key':vale}
print("Author:{name}, Blog: {url}".format(**site))
# 通过列表索引设置参数
my_list = ['xpt', 'https://xxpt.github.io/xxpt.github.io/']
print("Author:{0[0]}, Blog: {0[1]}".format(my_list)) # "0" 是必须的
my_list2 = ['baidu','https://www.baidu.com/']
print("sitename:{1[0]}, url: {1[1]}".format(my_list,my_list2))
可以向 str.format() 传入对象
class authorage(object):
def __init__(self, value):
self.value = value
author_age = authorage(18)
print('Author age: {0.value}'.format(author_age))
# 0可以去掉,0表示format函数里第一个对象,.value取属性值
str.format() 格式化数字的方法
1、精度格式化
描述 | 格式 |
---|---|
保留小数点后两位 | {:.2f} |
显示符号,并保留小数点后三位(+ 表示在正数前显示 +,负数前显示 -) | {:+.3f} |
不带小数 | {:.0f} |
print("{:.2f}".format(3.1415926))#保留小数点后两位
print("{:+.3f}".format(3.1415926))#带符号保留小数点后两位
print("{:.0f}".format(-3.1415926))#不带小数
2、b、d、o、x分别是二进制、十进制、八进制、十六进制
print('{:b}'.format(11))
print('{:d}'.format(11))
print('{:o}'.format(11))
print('{:x}'.format(11))
3、以逗号分隔的数字、百分比格式、指数记法
描述 | 格式 |
---|---|
以逗号分隔的数字 | {:,} |
百分比格式 | {:.2%} |
指数记法 | {:.2e} |
print("{:,}".format(100000))#以逗号分隔的数字
print("{:.2%}".format(0.23456))#百分比格式
print("{:.2e}".format(0.23456))#指数记法
填充与对齐
关于对齐:
^、<、>分别是居中、左对齐、右对齐,后面带宽度数字
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
描述 | 格式 |
---|---|
右对齐 (宽度为10) | {:>10d} |
左对齐 (宽度为10) | {:<10d} |
中间对齐 (宽度为10) | {:^10d} |
关于填充:
宽度指的是填充完的总宽度
描述 | 格式 |
---|---|
数字补零 (填充左边, 宽度为2) | {:0>2d} |
数字补x (填充右边, 宽度为4) | {:x<4d} |
可以使用大括号 {} 来转义大括号
print ("{} 对应的位置是 {{12}}".format("abc"))