Python基础--使用字符串
2016-03-13 22:46
645 查看
字符串是不可变序列
字符串格式化–%
%左侧放置一个字符串,右侧放置希望格式化的值:
如果字符串里包含百分号,那么就需要使用%%表示百分号。
%s中的s表示的是字符串,如果格式化浮点数,希望保留三位小数,则可以使用%.3f
元组作为%后面的参数,需要使用圆括号
字段宽度和精度
find方法
查找子字符串,返回子串所在位置最左端的索引,没找到则返回-1
join方法
split的逆方法,要连接的必须是字符串
lower方法
返回字符串小写字母版本
replace方法
返回某字符串的所有匹配项均被替换后得到的字符串
split方法
join的逆方法,将字符串分隔成序列
strip方法
返回去除两侧空格的字符串,注意不包括内部
translate方法
与前面的replace有些类似,但还有不同。
首先使用maketrans完成一张转换表,然后调用translate方法
就是字符串中的c变为k, s变为z
[code]>>>website = 'http://www.python.org' >>>website[-3:] = 'com' #错误
字符串格式化–%
%左侧放置一个字符串,右侧放置希望格式化的值:
[code]>>>format = 'Hello %s %s enough for ya?' >>>values = ('world', 'hot') >>>print format % values Hello world hot enough for ya?
如果字符串里包含百分号,那么就需要使用%%表示百分号。
%s中的s表示的是字符串,如果格式化浮点数,希望保留三位小数,则可以使用%.3f
元组作为%后面的参数,需要使用圆括号
[code]>>>'%s plus %s equals %s' % (1, 1, 2) '1 plus 1 equals 2'
字段宽度和精度
[code]#字段宽度为10, 精度为2 >>>%10.2f % pi '3.14'
find方法
查找子字符串,返回子串所在位置最左端的索引,没找到则返回-1
[code]>>>'With a moo-moo here, and a moo-moo there'.find('moo') 7 >>>'With a moo-moo here, and a moo-moo there'.find('shit') -1
join方法
split的逆方法,要连接的必须是字符串
[code]>>>seq = ['1', '2', '3'] >>>sep = '+' >>>seq.join(sep) '123+'
lower方法
返回字符串小写字母版本
[code]>>>'HELLO, worldD'.lower() hello, world
replace方法
返回某字符串的所有匹配项均被替换后得到的字符串
[code]>>>'This is a test'.replace('is', 'eez') 'Theez eez a test'
split方法
join的逆方法,将字符串分隔成序列
[code]>>>'1+2+3+4+5'.split('+') ['1', '2', '3', '4', '5']
strip方法
返回去除两侧空格的字符串,注意不包括内部
[code]>>>' internal whitespace is kept '.strip() 'internal whitespace is kept'
translate方法
与前面的replace有些类似,但还有不同。
首先使用maketrans完成一张转换表,然后调用translate方法
[code]>>>from string import maketrans >>>table = maketrans('cs', 'kz') >>>'this is an incredible test'.translate(table) 'thiz iz an inkredible tezt'
就是字符串中的c变为k, s变为z
相关文章推荐
- python之Class属性定义和访问
- Python学习笔记之基本数据类型
- Python中的threading
- python中单元测试doctest | unittest
- python(5)–random模块及验证码
- python_string常用函数用法小结
- python(5)–datetime模块
- 【零基础入门学习Python笔记013】元祖:戴上了枷锁的列表
- python 爬小说+beautifulsoup安装
- [Python] 记录
- Python中sys模块
- Python设计模式(4)-装饰模式
- Ansible源码分析之Python的multiprocessing模块使用
- python str.format 和 %占位符 区别
- python ORM 模块peewee(一): 建立数据库对象
- Python设计模式(3)-工厂方法模式
- python(5) - time模块
- leetcode 337. House Robber III-动态规划|Java|Python简洁高效
- Python设计模式(2)-策略模式
- python笔记之字符串格式化