python format用法详解
format 基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。
format基本用法
"Hello {0} {1}".format("Chen","xin") # 引用第一个参数
# 输出 'Hello Chen xin'"{} is cute".format("Chen xin") # 引用第一个参数
# 输出 'Chen xin is good'"My name is {name}".format(name="Chen xin") # 引用名字为name的参数
# 输出 'My name is Chen xin'
1. 类型转换
!s
!r
"Chen xin is a cute {!s}".format("baby") # !s 相当于对于参数调用str()
# 输出 'Peppa pig is a cute baby'"Chen xin is a cute {!r}".format("baby") # !r 相当于对于参数调用repr()
# 输出 "Peppa pig is a cute 'baby'"
2. 通过位置来填充字符串
print('{0}, {1}, {2}'.format('a', 'b', 'c')) # a, b, c
print('{}, {}, {}'.format('a', 'b', 'c')) # a, b, c
print('{2}, {1}, {0}'.format('a', 'b', 'c')) # c, b, a
print('{2}, {1}, {0}'.format(*'abc')) # c, b, a
print('{0} {1} {0}'.format('aa', 'bb')) # aa bb aa
同一个参数可以填充多次,这个是format比%先进的地方
3. 按名称访问参数
print('name: {last_name}{first_name}'.format(last_name='chen', first_name='xin'))
# name: chenxinname= {'last_name': 'chen', 'first_name': 'xin'}
print('name: {last_name}, {first_name}'.format(**name))
# name: chenxin
4. 通过参数属性访问
class MyList:def __init__(self, x, y):self.x, self.y = x, ydef __str__(self):return 'MyList({self.x}, {self.y})'.format(self = self)print(str(MyList('陈新明', 'www.chenxm.cc')))# 网站名:陈新明, 地址 www.chenxm.cc
5. 通过参数的items访问
my_list = ['陈新明', 'www.chenxm.cc']print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的# 网站名:陈新明, 地址 www.chenxm.cc
6. 对齐字符串
"{:>5}".format(1) # 设置宽度为5,右对齐
"{:>5}".format(10)
"{:>5}".format(100)
"{:>5}".format(1000)
# 输出下面的结果
' 1'
' 10'
' 100'
' 1000'print('{:_<30}'.format('left aligned'))
#'left aligned__________________'print('{:_>30}'.format('right aligned'))
#'__________________right aligned'print('{:_^30}'.format('centered'))
#'__________________centered__________________'
^ 居中 后面带宽度,
< 左对齐 后面带宽度,
> 右对齐 后面带宽度,
: 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
7. 截断字符串
'{:.5}'.format('Hello Chen') # 截取前5个字符
# 输出 'Hello'
8. 数字格式化
print("{:.2f}".format(3.1415926));# 3.14
+ 表示在正数前显示 +,
- 负数
(空格) 表示在正数前加空格
b 二进制
d 十进制
o 八进制
x 十六进制
更多样式
9. 使用逗号作为千位分隔符
print('{:,}'.format(1234567890))#'1,234,567,890'
10. 表示一个百分比
print('number: {:.2%}'.format(0.61898))# number: 61.90%
11. 时间格式化
import datetimed = datetime.datetime(2018, 7, 31, 15, 58, 58)
print('{:%Y-%m-%d %H:%M:%S}'.format(d))# 2018-07-31 15:58:58
12. 访问元组中的元素
a = (1,2)
'X: {0[0]}; Y: {0[1]}'.format(a)
# 输出 'X: 1; Y: 2'
# 注意:用%格式化字符串不支持此功能
13. 访问字典中的元素
people = {"name": "Chen", "age": 18}
"My name is {p[name]} and my age is {p[age]}".format(p=people )# 输出 'My name is Chen and my age is 18'
# 注意:用%格式化字符串不支持此功能
原文:python format用法详解
python format用法详解相关推荐
- python中print format的用法-python format用法详解
format 基本语法是通过 {} 和 : 来代替以前的 % . format 函数可以接受不限个参数,位置可以不按顺序. format基本用法 "Hello {0} {1}".f ...
- python中format的用法-python format用法详解
format 基本语法是通过 {} 和 : 来代替以前的 % . format 函数可以接受不限个参数,位置可以不按顺序. format基本用法 "Hello?{0}?{1}".f ...
- python format()用法详解
str.format() 这个特性从python2.6而来 其实实现的效果和%有些类似 不过有些地方更方便 通过位置映射: In [1]: '{0},{1}'.format('kzc',18) Out ...
- access中的Format用法详解
access中的Format用法详解 Format$(Now,"EEOA") 只要这么一句~~~~~就可以得到" 二○○六年五月二十六日" ---------- ...
- 技巧 | Python 字典用法详解(超全)
文章目录 1.dict.clear() 2.dict.copy() 3.dict.fromkeys() 4.dict.get() 5.dict.items() 6.dict.keys() 7.dict ...
- python redis用法详解
使用python来操作redis用法详解 1.1 2017.06.22 16:38* 字数 4875 阅读 96923评论 8喜欢 60 1.redis连接 redis提供两个类Redis和Stric ...
- python yield 用法详解
python yield 生成器 文章目录 python yield 生成器 1. 背景 2. 如何生成斐波那契數列 清单 1. 简单输出斐波那契數列前 N 个数 清单 2. 输出斐波那契數列前 N ...
- Python break用法详解
文章目录 Python break 用法 Python break 用法 我们知道,在执行 while 循环或者 for 循环时,只要循环条件满足,程序将会一直执行循环体,不停地转圈.但在某些场景,我 ...
- Python正则表达式用法详解
搞懂 Python 正则表达式用法 作者:枫叶云 来源:见文末 Python 正则表达式 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配. Python 自1.5版本 ...
最新文章
- c4d教程-太空火车站场景创作视频教程Skillshare – Create A Space Train Scene With Cinema 4D Redshift Render
- Python 语法相关知识
- PowerDesigner中使用vbscript访问对象进行批量操作
- Ubuntu系统目录结构
- Servlet的学习(四)
- 参加51CTO组织的2013云计算架构师大会
- Oracle Vm VirtualBox中安装Ubantu
- pthread_cleanup_push()/pthread_cleanup_pop()
- android.util.typedvalue的jar包,android – 了解Typed值类
- PCL中3D点云特征描述与提取(一)
- [Photography] 还是DPP好!
- 英文情景对话(背诵篇)
- myeclipse设置黑色主题
- 【ITSM】什么是ITSM,IT部门为什么需要ITSM
- Java 八皇后游戏
- python项目 from models import * 报错
- c++文件保存与读取
- /home/www/easyadmin/vendor/topthink/think-helper/src/helper.php 报错处理
- xp无线网卡开启的服务器,笔记本xp系统开启无线网卡的方法
- python基础--初识python