(转)Python 字符串格式化 str.format 简介
原文:https://www.cnblogs.com/wilber2013/p/4641616.html
http://blog.konghy.cn/2016/11/25/python-str-format/
Python 在 2.6 版本中新加了一个字符串格式化方法: str.format()。它的基本语法是通过 {} 和 :来代替以前的 %.。格式化时的占位符语法:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
“映射”规则
通过位置
str.format() 可以接受不限个参数,位置可以不按顺序:
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
通过关键字参数
使用关键参数时字符串中需要提供参数名:
>>> "I am {name}, age is {age}".format(name="huoty", age=18)
'I am huoty, age is 18'
>>> user = {"name": "huoty", "age": 18}
>>> "I am {name}, age is {age}".format(**user)
'I am huoty, age is 18'
通过对象属性
str.format() 可以直接读取用户属性:
>>> class User(object):
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
... def __str__(self):
... return "{self.name}({self.age})".format(self=self)
...
... def __repr__(self):
... return self.__str__()
...
...
>>> user = User("huoty", 18)
>>> user
huoty(18)
>>> "I am {user.name}, age is {user.age}".format(user=user)
'I am huoty, age is 18'
通过下标
在需要格式化的字符串内部可以通过下标来访问元素:
>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]
>>> "I am {0[0]}, age is {1[2]}".format(names, ages)
'I am huoty, age is 8'
>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}
>>> "I am {names[0]}, age is {ages[0]}".format(**users)
指定转化
可以指定字符串的转化类型:
conversion ::= "r" | "s" | "a"
其中 "!r" 对应 repr(); "!s" 对应 str(); "!a" 对应 ascii()。 示例:
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
格式限定符
填充与对齐
填充常跟对齐一起使用。^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
>>> "{:>8}".format("181716")
' 181716'
>>> "{:0>8}".format("181716")
'00181716'
>>> "{:->8}".format("181716")
'--181716'
>>> "{:-<8}".format("181716")
'181716--'
>>> "{:-^8}".format("181716")
'-181716-'
>>> "{:-<25}>".format("Here ")
'Here -------------------->'
浮点精度
用 f 表示浮点类型,并可以在其前边加上精度控制:
>>> "[ {:.2f} ]".format(321.33345)
'[ 321.33 ]'
>>> "[ {:.1f} ]".format(321.33345)
'[ 321.3 ]'
>>> "[ {:.4f} ]".format(321.33345)
'[ 321.3335 ]'
>>> "[ {:.4f} ]".format(321)
'[ 321.0000 ]'
还可以为浮点数指定符号,+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格,在幅负数前加 -;- 与什么都不加({:f})时一致:
>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)
'+3.141593; -3.141593'
>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)
' 3.141593; -3.141593'
>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)
'+3.1416; -3.1416'
截取字符串
截取字符串类似于浮点精度控制,只是不需要加 f 在指定是浮点数:
>>> '{:.2}'.format("hello")
'he'
>>> '{:.3}'.format("huayong")
'hua'
指定进制
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(18)
'int: 18; hex: 12; oct: 22; bin: 10010'
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18)
'int: 18; hex: 0x12; oct: 0o22; bin: 0b10010'
千位分隔符
可以使用 "," 来作为千位分隔符:
>>> '{:,}'.format(1234567890)
'1,234,567,890'
百分数显示
>>> "progress: {:.2%}".format(19.88/22)
'progress: 90.36%'
事实上,format 还支持更多的类型符号:
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
其他技巧
占位符嵌套
某些时候占位符嵌套还是很有用的:
>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')
'*****hello******'
>>>
>>> for num in range(5,12):
... for base in "dXob":
... print("{0:{width}{base}}".format(num, base=base, width=5), end=' ')
... print()
...
...
5 5 5 101
6 6 6 110
7 7 7 111
8 8 10 1000
9 9 11 1001
10 A 12 1010
11 B 13 1011
作为函数使用
可以先不指定格式化参数,而是在不要的地方作为函数来调用:
>>> email_f = "Your email address was {email}".format
>>> print(email_f(email="suodhuoty@gmail.com"))
Your email address was sudohuoty@gmail.com
转义大括号
当在字符串中需要使用大括号时可以用大括号转义:
>>> " The {} set is often represented as { {0} } ".format("empty")
' The empty set is often represented as {0} '
(转)Python 字符串格式化 str.format 简介的更多相关文章
- python字符串格式化方法 format函数的使用
python从2.6开始支持format,新的更加容易读懂的字符串格式化方法, 从原来的% 模式变成新的可读性更强的 花括号声明{}.用于渲染前的参数引用声明, 花括号里可以用数字代表引用参数的序 ...
- python字符串格式化之format
用法: 它通过{}和:来代替传统%方式 1.使用位置参数 要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表 ...
- python 字符串格式化 ( 百分号 & format )
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存. ----百分号 tpl = ...
- 字符串格式化str.format
一.字符串格式化之str.format 1.位置参数:用{0},{1},{2}表示位置 v1 = '{1},{0},{1}'.format('a','b') #输出b,a,b 2.关键词参数:用{na ...
- 一文秒懂!Python字符串格式化之format方法详解
format是字符串内嵌的一个方法,用于格式化字符串.以大括号{}来标明被替换的字符串,一定程度上与%目的一致.但在某些方面更加的方便 1.基本用法 1.按照{}的顺序依次匹配括号中的值 s = &q ...
- 【Python】更优的字符串格式化方式 -- "format"替代"%s"
背景 前段时间看了一篇介绍Python的代码技巧的文章,建议格式化字符串时使用"format"代替使用"%",但是没有说明原因.各博客网站介绍相关用法的博客很多 ...
- python字符串格式化 %操作符 {}操作符---总结
Python字符串格式化 (%占位操作符) 在许多编程语言中都包含有格式化字符串的功能,比如C和Fortran语言中的格式化输入输出.Python中内置有对字符串进行格式化的操作 %. 模板 格式化字 ...
- 【转】Python字符串格式化
Python 支持格式化字符串的输出 .尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中. 在 Python 中,字符串格式化使用与 C 中 sp ...
- 7. python 字符串格式化方法(2)
7. python 字符串格式化方法(2) 紧接着上一章节,这一章节我们聊聊怎样添加具体格式化 就是指定替换字段的大小.对齐方式和特定的类型编码,结构如下: {fieldname!conversion ...
随机推荐
- python sublime run快捷键设置
一.Ctrl+Shift+P进行插件“sublimeREPL”安装 二.打开preferences->Key Binding-User,写入以下内容 [ { "keys": ...
- select for update [nowait]
Syntax The NOWAIT and WAIT clauses let you tell the database how to proceed if the SELECT statement ...
- fakeapp, faceswap, deepfacelab等deepfakes换脸程序的简单对比
https://deepfakes.com.cn/index.php/95.html https://www.cnblogs.com/zackstang/p/9011753.html
- Linux 基础教程 34-软件包管理-RPM
对于Linux而言管理各类软件,如安装.卸载和升级等是常有的事情和必备的技能.以CentOS为例,常用的安装包命令有rpm和yum. RPM基础 RPM(RedHat Package ...
- CodeForces 572D Minimization(DP)
题意翻译 给定数组AAA 和值kkk ,你可以重排AAA 中的元素,使得∑i=1n−k∣Ai−Ai+k∣\displaystyle\sum_{i=1}^{n-k} |A_i-A_{i+k}|i=1∑n ...
- Give $20/month and provide 480 hours of free education
Hi , Hope all is well. Summer is right around the corner, and the Khan Academy team is excited to sp ...
- Android-SurfaceView生命周期
SurfaceView的生命周期,和 Activity生命周期,Service生命周期,BroadcastReceiver生命周期,等,不一样: 因为SurfaceView显示的是(视频画面,游戏画面 ...
- python面试题之如何计算一个字符串的长度
在我们想计算长度的字符串上调用函数len()即可 >>> len('hhhhhhhhjg') 10 所属网站分类: 面试经典 > python 作者:外星人入侵 链接:http ...
- Linux Guard Service - 杀死守护进程
杀死某个子进程 杀死守护进程的子进程后,改进程会变为僵尸进程 14087 ? Ss 0:00 ./test4-1 14088 ? S 0:00 \_ ./test4-1 14089 ? S 0:00 ...
- WIN7或2008远程连接特别慢的解决方法 【转】
方法一. 原因在于从vista开始,微软在TCP/IP协议栈里新加了一个叫做“Window Auto-Tuning”的功能.这个功能本身的目的是为了让操作系统根据网络的实时性能,(比如响应时间)来动态 ...