Python格式化输出(format)

格式化输出(format)

1.基本用法

"hello {}".format("python") # 引用一个参数       传字符串
# 输出:hello python

"hello {}".format(1024)                        # 传数字
# 输出:hello 1024

"hello {}".format([1, 2, 3, 4])                # 传列表
# 输出:hello [1, 2, 3, 4]

"hello {}".format((1, 2, 3, 4))                # 传元组
# 输出:hello (1, 2, 3, 4)

"hello {}".format({"name": "chenkia", "age": 18})    # 传字典
# 输出:hello {'name': 'chenkia', 'age': 18}

"hello {}".format({"name", "chenkai", "name", "akai"})    # 传集合
# 输出:hello {'chenkai', 'akai', 'name'}

Python3.6版本之后的新写法

str = python

print(f"hello {str}" )  # 引用一个变量 

输出:hello python

其它参数选项

字符串的参数使用{NUM}进行表示,0, 表示第一个参数,1, 表示第二个参数, 以后顺次递加;

使用”:”, 指定代表元素需要的操作, 如”:.3”小数点三位, “:8”占8个字符空间等;

还可以添加特定的字母, 如:

‘b’ - 二进制. 将数字以2为基数进行输出.

‘c’ - 字符. 在打印之前将整数转换成对应的Unicode字符串.

‘d’ - 十进制整数. 将数字以10为基数进行输出.

‘o’ - 八进制. 将数字以8为基数进行输出.

‘x’ - 十六进制. 将数字以16为基数进行输出, 9以上的位数用小写字母.

‘e’ - 幂符号. 用科学计数法打印数字, 用’e’表示幂.

‘g’ - 一般格式. 将数值以fixed-point格式输出. 当数值特别大的时候, 用幂形式打印.

‘n’ - 数字. 当值为整数时和’d’相同, 值为浮点数时和’g’相同. 不同的是它会根据区域设置插入数字分隔符.

‘%’ - 百分数. 将数值乘以100然后以fixed-point(‘f’)格式打印, 值后面会有一个百分号.

2.传入多个参数

"My name is {name}, I am {age} years old".format(name="chenkai", age=18) # 别名替换

"My name is {0}, I am {1} years old".format("chenkai", 18)

"My name is {name}, I am {age} years old".format_map({"name": "chenkai", "age": 18})

# 输出:"My name is chenkai, I am 18 years old"

3.进制转换

"{0} in HEX is {0:#x}".format(16)

# 输出:"16 in HEX is 0x10"
"{0} is OCT is {0:#o}".format(16)

# 输出:"16 is OCT is 0o20"

4.对齐字符串

"{:>5}".format(1)        # 设置宽度为5,右对齐(.rjust()方法)

"{:>5}".format(10)      

"{:>5}".format(100)

"{:>5}".format(1000)

# 输出下面的结果

"    1"

"   10"

"  100"

" 1000"
'{:_<10}'.format('test') # 左对齐(.ljust()方法),并且指定"_"填充空白部分

# 输出 'test______'
'{:_^10}'.format('test') # 居中对齐(.center()方法),并且指定"_"填充两侧

# 输出 '___test___'

# 用%格式化字符串不支持居中对齐

5.截断字符串

"{:.5}".format("Hello Python") # 截取前5个字符

# 输出:"Hello"

6.访问对象属性

class Pig(object):

    def __init__(self, name, age, weight):

        self.name = name

        self.age = age 

        self.weight =weight

    def __repr__(self):

        return "Pig name={0}, age={1}".format(self.name, self.age)

pig = Pig("warrior", 26, 100)

print("{0} is {1} years old, {2} kilograms".format(pig.name, pig.age, pig.weight))

# 输出:"warrior is 26 years old, 100 kilograms"

7.时间格式化

from datetime import datetime

'{:%Y-%m-%d %H:%M}'.format(datetime(2018, 5, 19, 21, 00))

# 输出 '2018-05-19 21:00'

8.传入指定参数

"{:{char}{align}{width}}".format("test", char="_", align="^", width="10")

# 输出 "___test___"
from datetime import datetime

dt = datetime(2018, 5, 24, 21, 0)

"{:{dfmt} {tfmt}}".format(dt, dfmt="%Y-%m-%d", tfmt="%H:%M")

# 输出 "2018-05-24 21:00"

猜你喜欢

转载自blog.csdn.net/m0_37714245/article/details/81750784