一、字符串
1、一个字符串可以存放任意数量的字符。如:"hello" 'cwc' """vwerv"""。
2、字符串是有序的,每个字符都有其对应的下标,与列表一致。
3、字符串不可变、有序、可遍历。
二、字符串切片
与列表切片类似
1、语法结构
序列对象[开始索引:结束索引:步长] 注意:(1)步长为间隔几个元素取用。 (2)截取出的元素包含开始索引,不包含结束索引。 (3)开始索引不指定的话默认为0,结束索引默认列表长度,步长默认为1 (4)步长为-1,表示从后向前截取,s[-1:-7:-1]2、示例
s="hello-word" #获取 print(s[2]) #切片 print(s[1:5:2])结果
三、字符串常用方法
1、常用方法
| find() | 在字符串中查找子串,返回第一次出现的索引位置,找不到返回-1 | s.find('hello') |
| count() | 统计子串在字符串中出现的次数 | s.count('h') |
| upper() | 将字符串中的所有字母转换为大写 | s.upper() |
| lower() | 将字符串中的所有字母转换为小写 | s.lower() |
| split() | 将字符串按指定分隔符分割成列表 | s.split(' ') |
| strip() | 去除字符串两端的空白字符或指定字符 | s.strip() / s.strip('*') |
| replace() | 将字符串中指定子串替换为新的子串 | s.replace('H','C') |
| startswith() | 检查字符串是否以指定子串开头,返回布尔值 | s.startswith('p') |
| endswith() | 检查字符串是否以指定子串结尾,返回布尔值 | s.endswith('d') |
2、示例
s="hello-word" s1="DECK" s2=" abc " print(s.find('l')) #找到返回下标 print(s.find('f')) #没找到返回-1 print(s.count('o')) #统计o出现的次数 print(s.upper()) #转大写 print(s1.lower()) #转小写 print(s.split('-')) #字符串切割 print(s2.strip()) #去除字符串两端空格 print(s.strip('d')) #去除指定字符 print(s.replace('h','H')) #替换 print(s.startswith('h')) #判断字符串是否以h开头 print(s.endswith('d')) #判断字符串是否以d结尾结果
3、判断指定的子字符串是否出现在字符串中用 in 。