博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python字符串处理常用方法
阅读量:4170 次
发布时间:2019-05-26

本文共 2135 字,大约阅读时间需要 7 分钟。

1》str.find()  str.rfind()  str.index()  str.rindex()  str.count()
>>> s='hello python,hello world!'
>>> s.find('hello')#从左侧开始查找
0
>>> s.rfind('hello')#从右侧开始查找
13
>>> s.find('wahaha')#查找失败,返回-1
-1
>>> s.index('hello')#从左侧开始查找
0
>>> s.rindex('hello')#从右侧开始查找
13
>>> s.index('wahaha')#查找失败,抛出ValueError异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.count('hello')#查找子串的个数
2
2》str.capitalize()  str.lower()  str.upper() str.swapcase()
>>> s='hello python,HELLO world!'
>>> s.capitalize()#首字母大写,其余的小写
'Hello python,hello world!'
>>> s
'hello python,HELLO world!'
>>> s.lower()#全部小写
'hello python,hello world!'
>>> s
'hello python,HELLO world!'
>>> s.upper()#全部大写
'HELLO PYTHON,HELLO WORLD!'
>>> s
'hello python,HELLO world!'
>>> s.swapcase()#大小写互换
'HELLO PYTHON,hello WORLD!'
3》str.split()  str.join()
>>> s='python   hello\n\nworld\t\twahaha\r\rabc'
>>> s.split()#默认以 空格或'\n'或'\t'或'\r'为分割符,返回一个列表,列表中不包含空串
['python', 'hello', 'world', 'wahaha', 'abc']
>>> s='hello   python '
>>> s.split(' ')#指定以空格为分隔符,返回的列表中可能包含空串
['hello', '', '', 'python', '']
>>> l=['abc','def','gh']
>>> '+'.join(l)#以'+'作为连接符
'abc+def+gh'
>>> l
['abc', 'def', 'gh']
>>> ''.join(l)#以空串作为连接符
'abcdefgh'
4》len(str)
>>> s='abc'
>>> len(s)#求字符串的长度
3
>>> s='连接符'
>>> s
'\xe8\xbf\x9e\xe6\x8e\xa5\xe7\xac\xa6'
>>> len(s)
9
>>> s=u'连接符'
>>> s
u'\u8fde\u63a5\u7b26'
>>> len(s)
3
5》cmp(str1,str2)
>>> help(cmp)
Help on built-in function cmp in module __builtin__:
cmp(...)
    cmp(x, y) -> integer
    Return negative if x<y, zero if x==y, positive if x>y.
>>> cmp('abc','ef')# 'abc'<'ef'
-1
>>> cmp('abc','aBC')# 'abc'>'aBC'
1
>>> cmp('abc','abc')# 'abc'=='abc'
0
6》max(str) min(str)
>>> s='abcdefg'
>>> max(s)
'g'
>>> min(s)
'a'
7》str.startswith()  str.endswith()
>>> s='hello python hello world!'
>>> s.startswith('hell')
True
>>> s.startswith('ok')
False
>>> s.endswith('!')
True
>>> s.endswith('wahaha!')

False

8》str.replace()

>>> s='hello python,hello world!'

>>> s.replace('hello','love')#找到了,就替换
'love python,love world!'
>>> s
'hello python,hello world!'
>>> s.replace('love','LOVE')#找不到,就不换
'hello python,hello world!'

(完)

转载地址:http://acyai.baihongyu.com/

你可能感兴趣的文章
mysql中用命令行复制表结构的方法
查看>>
hbase shell出现ERROR: org.apache.hadoop.hbase.ipc.ServerNotRunningYetException
查看>>
让代码变得更优雅-Lombok
查看>>
解决Rhythmbox乱码
查看>>
豆瓣爱问共享资料插件发布啦
查看>>
Ubuntu10.10 CAJView安装 读取nh\kdh\caj文件 成功
查看>>
kermit的安装和配置
查看>>
vim 配置
查看>>
openocd zylin
查看>>
进程创建时文件系统处理
查看>>
内核线程创建
查看>>
linux中cat命令使用详解
查看>>
java中的异常机制
查看>>
java SE面向对象思维导图
查看>>
三维分析之视频投放
查看>>
SuperMap iDesktop之栅格值怎么查
查看>>
SuperMap iClient3D for WebGL教程-orientation
查看>>
SuperMap iClient3D for WebGL教程-description描述属性
查看>>
SuperMap iClient3D for WebGL教程-CallbackProperty
查看>>
如何修改leaflet聚合图的层级和样式
查看>>