Python 使用字符串
来源:互联网 发布:片头制作软件 编辑:程序博客网 时间:2024/06/01 18:07
字符串格式化:用%来实现,格式化字符串的%s——转换说明符,%%表示一个%
>>> format = "Hello, %s, %s enough for ya?"
>>> values = ('world', 'Hot')
>>> print format % values
Hello, world, Hot enough for ya?
注:用列表和其他的序列代替元组,那么序列只解释为一个值
>>> format = "Pi with three decimals: %.3f"
>>> from math import pi
>>> print format % pi
Pi with three decimals: 3.142
(1)%字符:标记转换说明符的开始
(2)转换标志(可选):-表示左对齐,表示在转换值之前要加上正负号,“”(空白符)表示正数之前保留空格;0表示转换值若位数不够则用0填充。
(3)最小字段宽度(可选):转换后的字符串知识应该具有该指定的宽度。如果是*,则宽度会从元组读出。
(4)点(.)后跟精度值(可选):如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度,如果是*,那么精度会从元组中读出。
(5)转换类型:d,i、o、u、x、X、e、E、f,F、g、G、C、r、s
例子:
#使用给定的宽度打印格式化后的价格列表
width = input('Please enter width: ')
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
format = '%-*s%*.2f'
print '=' * width
print header_format % (item_width, 'Item', price_width, 'Price')
print '-' * width
print 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 (16 oz.)', price_width, 8)
print format % (item_width, 'Prunes (4 lbs.)', price_width, 12)
print '=' * width
输出:
Please enter width: 35
===================================
Item Price
-----------------------------------
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried Apricots (16 oz.) 8.00
Prunes (4 lbs.) 12.00
===================================
===================================
Item Price
-----------------------------------
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried Apricots (16 oz.) 8.00
Prunes (4 lbs.) 12.00
===================================
字符串方法:源于string模板
string.digits:包含数字0~9的字符串
string.letters:包含所有字母(大写或小写)的字符串
string.lowercase:包含所有小写字母的字符串
string.printable:包含所有可以打印的字符串
....
find方法
返回子串的位置,-1表示没有找到
join方法:它是split方法的逆方法,用来在队列中添加元素
队列元素必须是字符串,连接字符串列表
lower方法
转成小写字母
replace方法
查找并替换
split方法
join的逆方法,将字符串分割成序列
strip方法
默认去除字符串两侧的空格,也可以只定去除的字符,只限两侧的
translate方法
针对单个字符的替换操作,第二个参数是可选的,用于指定要删除的字符
- python字符串使用总结
- python 字符串使用总结
- Python字符串使用总结
- python字符串使用总结
- Python 使用字符串
- python 字符串使用
- python中的字符串使用
- python 字符串使用庄族壮紫拙鬃
- python字符串使用问题
- Python基础--使用字符串
- Python 使用字符串
- python中使用字符串
- Python使用字符串
- Python中使用中文字符串
- Python字符串join使用示例
- python中字符串的使用
- python笔记三-使用字符串
- Python 第三章 使用字符串
- 字符串:KMP Eentend-Kmp 自动机 trie图 trie树 后缀树 后缀数组
- 白盒测试的方法
- 国内主要开源镜像网站汇总
- uva 10010 Longest Match
- SimpleAdapter
- Python 使用字符串
- 如果腾讯开放IDC业务-2013年8月江西IDC排行榜与综述
- #pragma comment
- B. Road Construction
- POJ 1789 Truck History
- ADT下载地址整理
- UVA414—— Machined Surfaces
- Protel99SE 笔记
- poj 2289 Jamie's Contact Groups(二分+多重匹配)