python字符串处理常用方法

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!'

(完)

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值