跟我一起学Python之八:基本字符串和字符串格式化
来源:互联网 发布:淘宝一千多的充气娃娃 编辑:程序博客网 时间:2024/05/21 15:36
1.基本字符串操作
字符串是序列的一种,字符串是不可改变的。
>>> website='heep://www.python.org'>>> website'heep://www.python.org'>>> website[-3:]'org'
2.字符串格式化
[1]简单转换
精简版:
>>> format="hello, %s , %s enough for ya?" #%号代表有一个变量,s代表是字符串类型>>> values=("world","Hot")>>> print format % values #格式 print 格式化 % 变量值hello, world , Hot enough for ya?
>>> format = "pi whith three decimals:%.3f" #%号代表占位符,f代表字符串类型为浮点数,.3代表要3位小数>>> from math import pi>>> print format % pipi whith three decimals:3.142
>>> from string import Template >>> s = Template('$x, glorious $x!')>>> s.substitute(x='slurm!')'slurm!, glorious slurm!!'
>>> s=Template("It's ${X}tastic!") #替换的是单词的一部分就需要使用大括号>>> s.substitute(X='slurm')"It's slurmtastic!"
>>> '%s plus %s equals %s' % (1,2,3) #如果变量为元组需要加上小括号'1 plus 2 equals 3'
%出现,说明转换开始了。
s代表字符串;
C代表一个字符;
G代表大于-4;
g代表大于-4;
f代表十进制浮点数;
e代表科学技术法;
X代表十六进制;
d代表十进制整数;
[2]字段宽度和精度
宽度
>>> '%10f' % pi' 3.141593'
精度
>>> '%.2f' % pi'3.14'>>> '%.5s' % 'loooooool''loooo'
[3]符号、对齐和0填充
0填充
>>> '%010.2f' % pi'0000003.14
-号代表左对齐
>>> '%-10.2f' % pi'3.14 '
空格填充
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10) 10 -10>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10) +10 -10
e.g.width=input("please enter width: ")price_width=10item_width=width-price_widthheader_format="%-*s%*s" #标题格式format="%-*s%*.2f" #数据项格式print '=' * widthprint header_format % (item_width,"Item",price_width,"Price")print '-' * widthprint format % (item_width,'Apples',price_width,0.4)print format % (item_width,'Pears',price_width,0.5)print format % (item_width,'Cantaloupes',price_width,1.92)print format % (item_width,'Dried Apricots',price_width,8)print format % (item_width,'Prunes(4,lbs.)',price_width,12)print '-' * widthplease enter width: 35===================================Item Price-----------------------------------Apples 0.40Pears 0.50Cantaloupes 1.92Dried Apricots 8.00Prunes(4,lbs.) 12.00-----------------------------------
- 跟我一起学Python之八:基本字符串和字符串格式化
- 跟我一起学Python之四:字符串简介
- 跟我一起学Python之九:字符串常用方法
- 跟我一起学python(二),python基本数据类型
- 跟我一起学python(三),python基本数据类型和函数
- 跟我一起学Python之五:序列
- 跟我一起学Python之六:列表
- 跟我一起学Python之七:元组
- 跟我一起学Python之十:字典
- 跟我一起学Python之十一:字典方法
- 跟我一起学Python之一:数字和表达式
- 跟我学JavaScript--字符串
- 跟我一起学python(八),网络编程(基础篇)
- 跟我一起学C++之重载
- Python 字符串的基本格式化
- 看代码学编程之python字符串格式化
- 跟我一起学python(一),python基础
- 跟我一起学python(四),python的模块
- Reverse
- Android性能优化之布局优化
- 数组指针和指针数组的区别
- HDU 2566 统计硬币(O(m^3)枚举+优化成O(m))
- Guessing Game
- 跟我一起学Python之八:基本字符串和字符串格式化
- 《数据的游戏:冰与火》读后总结
- 查看linux服务器硬盘IO读写负载
- Encoding
- verilog中的initial语句
- POJ 3683 - Priest John's Busiest Day 构图2-sat..感觉求方案不太正确..要改进..
- OpenMeetings(4)----新用户注册
- JAVA-设计模式之备忘录模式
- windows多线程编程1