Python 第三章 使用字符串
来源:互联网 发布:sql server 2008 补丁 编辑:程序博客网 时间:2024/06/05 09:57
基本字符串操作:
所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最大值和最小值)对字符串同样适用。
但是,字符串都是不可变的。所以分片赋值是不合法的。
下面记录几种常用的字符串方法:
find
find方法能在一个字符串中查找子字符串,返回子字符串所在位置的最左端索引。
>>> 'haha,Hello, world.come on!'.find("Hello")
5 ----> 返回了要查找的子字符串所在字符串的索引位置
>>> 'haha,Hello, world.come on!'.find("ha")
0
>>> 'haha,Hello, world.come on!'.find("ba")
-1 ----> 若字符串中没有要查找的子字符串,则返回-1
>>> 'haha,Hello, world.come on!'.find("ha", 1)
2 --->第二个参数1, 设置了开始查找的起点索引号
>>> len('haha,Hello, world.come on!')
26
>>> 'haha,Hello, world.come on!'.find("om", 1, 25)
19 --->第三个参数25, 设置了查找的终点索引号
>>> 'haha,Hello, world.come on!'.find("om", 1, 19)
-1
join
join方法能连接字符串列表
>>> dirs = "", "usr", "bin", "env"
>>> dirs
('', 'usr', 'bin', 'env')
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print "c:"+"\\".join(dirs)
c:\usr\bin\env
>>>
split
split方法是join的逆方法,用来将字符串分隔成序列。
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5'] -->指定+为分隔符
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Centrify DirectAudut Agent'.split()
['Centrify', 'DirectAudut', 'Agent'] -->默认空格也分隔符
lower
lower方法能将字符串中大写字符转换成小写
>>> name = 'Louis'
>>> names = ['louis', 'cherish', 'tom', 'jad']
>>> if name.lower() in names:
print "Found it"
Found it
>>>
replace
replace方法替换字符串中所有匹配项,并将替换后的字符串返回
>>> 'this is a test.'.replace('is', 'eez')
'theez eez a test.'
strip
strip方法能将字符两侧空格去掉,然后返回前后无空格的字符串。
>>> ' hey, you are beautiful! '.strip()
'hey, you are beautiful!' --->字符串中间的空格依然保留
也可以指定需要去除的字符。
>>> "*****----Here you are----******".strip('*-')
'Here you are'
translate
translate方法能
- Python 第三章 使用字符串
- Python 基础教程第三章 使用字符串
- Python学习笔记-第三章 使用字符串
- 《python基础教程》第三章 使用字符串
- Python基础教程-第三章-使用字符串
- 《Python 第三章》字符串
- Python第三章-字符串
- Python基础教程——第三章 使用字符串
- Python基础教程第三章——使用字符串
- 第三章 使用字符串
- 第三章 使用字符串
- python学习第三章----字符串
- Python基础教程 | 第三章 字符串
- python学习 第三章 使用字符串 《python基础教程第二版修订版》
- Python基础教程学习笔记----第三章 字符串
- python基础教程学习笔记 第三章 字符串
- 第三章-使用字符串——python基础教程(第二版)笔记
- 菜狗的Python学习笔记 第三章 字符串的使用
- [leetcode 164] Maximum Gap
- 摄像机跟随问题和粒子系统
- sgu128
- 文件——妖哥
- uvaoj 10791 Minimum Sum LCM 类似欧拉定理的写法
- Python 第三章 使用字符串
- 【GEngine】Unity脚本框架、Custom Inspector
- NYOJ 263 精 挑 细 选 (三次扫描)
- 第一篇 安卓系统的介绍及特点
- Java 访问控制权限
- 程序设计基石与实践之使用构造函数初始化对象
- nyoj-524
- NSArray排序的三种方法
- JAVA设计模式(五)——原型模式