Python之str操作

栏目: Python · 发布时间: 7年前

内容简介:Python之str操作

1. str.format():使用“{}”占位符格式化字符串(占位符中的索引号形式和键值对形式可以混合使用)。

 1 >>> string = 'python{}, django{}, tornado{}'.format(2.7, 'web', 'tornado')  # 有多少个{}占位符就有多少个值与其对应,按照顺序“填”进字符串中
 2 >>> string
 3 'python2.7, djangoweb, tornadotornado'
 4 >>> string = 'python{}, django{}, tornado{}'.format(2.7, 'web')
 5 Traceback (most recent call last):
 6   File "<pyshell#6>", line 1, in <module>
 7     string = 'python{}, django{}, tornado{}'.format(2.7, 'web')
 8 IndexError: tuple index out of range
 9 >>> string = 'python{0}, django{2}, tornado{1}'.format(2.7, 'web', 'tornado')  # 也可以指定“填”进去的值(从0开始,后面的值不一定都要用上,但是要保证指定的位置是有值的)
10 >>> string
11 'python2.7, djangotornado, tornadoweb'
12 >>> string = 'python{py}, django{dja}, tornado{tor}'.format(tor='tornado', dja='web', py=2.7)  # 可以使用键值对的形式赋值
13 >>> string
14 'python2.7, djangoweb, tornadotornado'
15 >>> 

2. 使用“%”进行字符串格式化。

格式化符号表
%c 转为单字符
%r 转为用repr()表达的字符串
%s 转为用str()表达的字符串
%d或%i 转为有符号的十进制整数
%u 转为无符号的十进制整数
%o 转为无符号的八进制整数
%x 转为无符号的十六进制整数,十六进制字母用小写表示
%X 转为无符号的十六进制整数, 十六进制字母用大写表示
%e 转为科学计数法表达的浮点数,其中的e用小写表示
%E 转为科学计数法表达的浮点数,其中的E用大写表示
%f或#F 转为浮点数
%g Python 根据数字的大小自动判断转换为%e或%f
%G 由Python根据数字的大小自动判断转换为%E或%F
%% 输出“%”
辅助格式化符号表
* 定义宽度或小数点的精度
- 左对齐
+ 对正数输出正值符号“+”
<sp> 数字的大小不足m.n的要求时,用空格补位
# 在八进制数前显示0,在十六进制数前显示0x或0X
0 数字的大小不足m.n的要求时,用0补位
m.n m是显示的最小总宽度,n是小数点后的位数(如果可用)

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Applications (Hacking Exposed)

Web Applications (Hacking Exposed)

Joel Scambray、Mike Shema / McGraw-Hill Osborne Media / 2002-06-19 / USD 49.99

Get in-depth coverage of Web application platforms and their vulnerabilities, presented the same popular format as the international bestseller, Hacking Exposed. Covering hacking scenarios across diff......一起来看看 《Web Applications (Hacking Exposed)》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具