python 内置数据结构字符串

python 字符串数据类型是常用的数据类型,字符串是有序的序列,是单个字符组合起来的集合,属于不可变类型,可迭代

  • 字符串初始化

#字符初始化 可以用单引号双引号三引号,三引号python中还可以作多行注释用
In [8]: t='hello'

In [9]: t="hello"

In [10]: t='''hello''

  

  • 字符串访问方式

In [18]: t='''hello'''
#索引方式
In [19]: t[2]
Out[19]: 'l'

In [20]: t[1]
Out[20]: 'e'
#支持负索引
In [21]: t[-1]
Out[21]: 'o'

  

  • 字符串连接

#连接字符串,join方法,‘连接符’.join('可迭代对象(字符类型)')
In [30]: ' '.join(['h','e','l','l','o'])
Out[30]: 'h e l l o'

In [35]: ' '.join(('h','e','l','l','o'))
Out[35]: 'h e l l o'

#+号链接两个字符串
In [39]: t
Out[39]: 'hello'

In [40]: t+'world'
Out[40]: 'helloworld'

  

  • 字符串分割

#字符串分割 split(sep=' ',maxsplit=-1) 默认按空格分隔,-1表示遍历整个可迭代对象,maxsplit表示分割多少次,分割完成返回一个列表
In [47]: t
Out[47]: 'h e l l o'

In [48]: t.split()
Out[48]: ['h', 'e', 'l', 'l', 'o']

In [49]: t.split('l')
Out[49]: ['h e ', ' ', ' o']
#分割次数
In [54]: t.split(' ',1)
Out[54]: ['h', 'e l l o']

In [55]: t.split(' ',2)
Out[55]: ['h', 'e', 'l l o']

  

#partition字符分割,会把字符串分割为(head,'sep',tail)的形式,分隔符必须有,当分隔符前后没匹配到则使用空白字符
In [64]: t='mysql=127.0.0.1'

In [65]: t.partition('=')
Out[65]: ('mysql', '=', '127.0.0.1')

#tail没有匹配
In [72]: t='mysql='

In [73]: t.partition('=')
Out[73]: ('mysql', '=', '')
#head无匹配
In [75]: t='=127.0.0.1'

In [76]: t.partition('=')
Out[76]: ('', '=', '127.0.0.1')

  

  • 字符串转换

#字符串大写
In [80]: t
Out[80]: 'hello'

In [81]: t.upper()
Out[81]: 'HELLO'
#字符串小写
In [85]: l
Out[85]: 'HELLO'

In [86]: l.lower()
Out[86]: 'hello'
#字符串大小写交换
In [88]: t='HeLlo'

In [89]: t.swapcase()
Out[89]: 'hElLO'

  

  • 字符串替换

#字符串替换replace(old,new,[count])
In [91]: t='hello'
#替换l为大写L
In [92]: t.replace('l','L')
Out[92]: 'heLLo'
#替换l为大写L,1次
In [93]: t.replace('l','L',1)
Out[93]: 'heLlo'

  

  • 去除两端特定字符串

#strip 方法去除两端特定字符串,默认去除空字符如\n \t 和空格等
In [109]: t
Out[109]: ' \n h e l l o \n \t'
#默认
In [112]: t.strip()
Out[112]: 'h e l l o'
#去除两端的\n \t 和空格
In [110]: t.strip('\n  \t')
Out[110]: 'h e l l o'
#去除特定的字符
In [118]: t='hello'

In [119]: t.strip('o')
Out[119]: 'hell'

In [120]: t.strip('ho')
Out[120]: 'ell'

  

字符串查找

#字符串查找 find('str',[start,[stop]]) start代表从那个位置开始查找,stop代表结束位置, 查找到该字符会返回 所在的索引,没有找到则返回-1
In [137]: s = "I am very very nice"

In [138]: s.find('very')
Out[138]: 5

In [139]: s.find('very',8)
Out[139]: 10

In [140]: s.find('very',5,9)
#找不到该字符串,返回-1

In [141]: s.find('good')
Out[141]: -1

  

  • 字符串计数

In [143]: s.count('very')
Out[143]: 2

  

  • 判断字符开始和结尾

#判断字符以什么字符开始和结尾返回bool型
In [154]: s
Out[154]: 'I am very very nice'
#以什么字符开始
In [155]: s.startswith('I')
Out[155]: True

In [156]: s.startswith('i')
Out[156]: False
#以什么字符结尾
In [157]: s.endswith('nice')
Out[157]: True

In [158]: s.endswith('good')
Out[158]: False

  

 

posted @ 2018-04-11 18:06  mictiger  阅读(443)  评论(0)    收藏  举报