Python format 用法详解

Stella981
• 阅读 760

一、填充字符串

1. 位置

print("hello {0}, this is {1}.".format("world", "python"))  # 根据位置下标进行填充
print("hello {}, this is {}.".format("world", "python"))  # 根据顺序自动填充
print("hello {0}, this is {1}. {1} is a new language.".format("world", "python"))  # 同一参数可以填充多次

输出:

hello world, this is python.
hello world, this is python.
hello world, this is python. python is a new language.

2. key

obj = "world"
name = "python"
print("hello {obj}, this is {name}.".format(obj = obj, name = name))

输出:

hello world, this is python.

3. 列表

list = ["world", "python"]
print("hello {names[0]}, this is {names[1]}.".format(names = list))

输出:

hello world, this is python.

4. 字典

dict = {"obj":"world", "name":"python"}
print("hello {names[obj]}, this is {names[name]}.".format(names = dict))

输出:

hello world, this is python.

注意:

访问字典的 key,不用引号。

5. 类属性

class Names():
    obj = "world"
    name = "python"

print("hello {names.obj}, this is {names.name}.".format(names = Names))

输出:

hello world, this is python.

6. 魔法参数

args = [",", "inx"]
kwargs = {"obj": "world", "name": "python"}
print("hello {obj}{} this is {name}.".format(*args, **kwargs))

输出:

hello world, this is python.

注意:

这里的 format(*args, **kwargs) 等价于 format(",", "inx", obj = "world", name = "python")

二、数字格式化

数字

格式

输出

描述

3.1415926

{:.2f}

3.14

保留小数点后两位

3.1415926

{:+.2f}

+3.14

带符号保留小数点后两位

-1

{:+.2f}

-1.00

带符号保留小数点后两位

2.71828

{:.0f}

3

不带小数

5

{:0>2d}

05

数字补零 (填充左边, 宽度为2)

5

{:x<4d}

5xxx

数字补x (填充右边, 宽度为4)

10

{:x<4d}

10xx

数字补x (填充右边, 宽度为4)

1000000

{:,}

1,000,000

以逗号分隔的数字格式

0.25

{:.2%}

25.00%

百分比格式

1000000000

{:.2e}

1.00e+09

指数记法

13

{:>10d}

13

右对齐 (默认, 宽度为10)

13

{:<10d}

13

左对齐 (宽度为10)

13

{:^10d}

13

中间对齐 (宽度为10)

11

'{:b}'.format(11)

1011

二进制

11

'{:d}'.format(11)

11

十进制

11

'{:o}'.format(11)

13

八进制

11

'{:x}'.format(11)

b

十六进制

11

'{:#x}'.format(11)

0xb

十六进制

11

'{:#X}'.format(11)

0xB

十六进制

三、其他用法

1. 转义

print("{{hello}} {{{0}}}".format("world"))

输出:

{hello} {world}

2. format 作为函数变量

name = "python"
hello = "hello, welcome to {} world!".format
print(hello(name))

输出:

hello, welcome to python world!

3. 格式化 datatime

from datetime import datetime
now = datetime.now()
print("{:%Y-%m-%d %X}".format(now))

输出:

2020-12-15 19:46:24

4. {}内嵌{}

print("hello {0:>{1}} ".format("world", 10))

输出:

hello      world

四、参考

python format 用法详解

Python format 格式化函数

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Stella981 Stella981
2年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
2年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这