频道栏目
首页 > 资讯 > Python > 正文

python:字符串基本用法及相关函数

17-09-06        来源:[db:作者]  
收藏   我要投稿

第一章:python

第二节:符串类型相关函数

1,字符串基本用法

成员关系,适用于字符串、元组和列表,成员关系分为in、not in
0 <= index <= len(sequence)-1
-len(sequence) <= index <= -1
切片从起始索引到结束索引
包括开始索引,不包括结束索引 (不包括结束索引对应的元素)
字符串格式转化符:
%s字符串,%d十进制数,
>>> '%.2f'%1234.56789
'1234.57'
>>> 'we are at %d%' % 100
'we are at 100%'
len():字符串,列表,元组长度
enumerate():循环取出索引值及字符,索引值在前,字符在后,适用于字符串,列表和元组
>>> s=[5, 6, 7, 8]
>>> enumerate(s)

>>> for i,t in enumerate(s):
... ····print i,t
0 5
1 6
2 7
3 8

2,字符串相关函数

import string

string.count(str, begin=0, end=len(string))
返回str在string里面出现的次数,如果begin或者end指定则返回指定范围内str出现的次数。
>>> st2='acacbbc'
>>> st2.count('a')
2

string.find(str, start=0, end=len(string))
检测str是否包含在string中,如果start和end指定范围,则检查是否包含在指定范围内,如果是,返回开始的索引值,否则返回-1
>>> st2='acacbbc'
>>> st2.find('b')
4

string.index(str, begin=0, end=len(string))
与string.find()用法相同,但如果str不在string中会抛出一个异常

string.join(seq) #不常用
以string作为分隔符,将seq中所有的元素(字符串表示)合并为一个新的字符串

string.lower()
转换string中所有大写字符为小写

string.upper()
转换string中所有小写字符为大写

string.replace(old, new[, max])
表示字符串的替换,将字符串old中的字符在string字符串中替换成new
old,在str字符串中存在的,且将别替换的子字符串
new,新字符串,用于替换old子字符串
max,可选字符串,替换不超过max次,如果不加入该参数,则new字符串将替换所有old字符串。
>>> s2='abbcdd'
>>> s2.replace('a', 'c')
'cbbcdd'
>>> s2.replace('d', 'c', 1)
'abbccd'

string.strip()
表示去掉字符串string左边或右边的’\t’,’\n’,’\s’(制表符,换行符和空格)
>>> s3='abc\n'
>>> s3.strip()
>>> s3
'abc'

string.split(str=”“, num=string.count(str)) #str=“”
以str为分隔符对string进行切片,如果num有指定值,则仅分割num个字符串
>>> s4='abbcdd'
>>> s4.split('b')
['a', '', 'cdd']
>>> s4.split('b', 1)
['a', 'bcdd']

string.partition(str)
该用法相当于string.find()和string.split()的结合体,从str出现的第一个位置其,把字符串string分成了一个3元组(string-pre-str, str, string-post-str)如果string中不包含str,则string-pre-str==string
>>> s5='abbcdd'
>>> s5.partition('a')
('', 'a', 'bbcdd')
>>> s5.partition('b')
('a', 'b', 'bcdd')

相关TAG标签
上一篇:java和c语言变长参数的底层实现区别
下一篇:LeetCode【4】Median of Two Sorted Arrays
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站