赞
踩
目录
字符串是字符的容器,一个字符串可以存放任意数量的字符。
如:字符串:“itheima”。
- my_str = "itcast and it"
- # 1. 通过下标索引取值
- value = my_str[0]
- value2 = my_str[-1]
- print(f"从字符串{my_str}取下标为0的元素。值为:{value},取下标为-1的元素。值为:{value2}")
-
- 从字符串itcast and it取下标为0的元素。值为:i,取下标为-1的元素。值为:t
同元组一样,字符串是一个:无法修改的数据容器。
- # 2. 查找特定字符串的下标索引值
- value = my_str.index("and")
- print(f"在字符串{my_str}中查找and,其起始下标是:{value}")
-
- 在字符串itcast and it中查找and,其起始下标是:7
语法:字符串.replace(字符串1,字符串2)
功能:将字符串内的全部:字符串1,替换为字符串2.
注意:不是修改字符串本身,而是得到了一个新字符串
- # 3. 字符串的替换
- new_my_str = my_str.replace("it","程序")
- print(f"将字符串{my_str},进行替换得到:{new_my_str}")
-
- 将字符串itcast and it,进行替换得到:程序cast and 程序
语法:字符串.split(分隔符字符串)
功能:按照指定的分隔符字符串,将字符串划分为多个字符串,并存入列表对象中
注意:字符串本身不变,而得到了一个列表对象
- # 4. 字符串的分割
- mystr = "hello python itcast"
- mystr_list = mystr.split(" ")
- print(f"将字符串{mystr}进行split切割得到:{mystr_list},类型是:{type(mystr_list)}")
-
- 将字符串hello python itcast进行split切割得到:['hello', 'python', 'itcast'],类型是:<class 'list'>
语法1:字符串.strip() #(不传入参数去前后空格)
- # 5. 字符串的规整操作(取前后空格)
- mystr = " hello python itcast "
- new_str = mystr.strip()
- print(f"字符串{mystr}被strip后,结果:{new_str}")
-
- 字符串 hello python itcast 被strip后,结果:hello python itcast
语法2:字符串.strip(字符串) #(去前后指定字符串)
- # 5. 字符串取除操作strip
- mystr = "12hello python itcast21"
- new_str = mystr.strip("12")
- print(f"字符串{mystr}被strip后,结果:{new_str}")
-
- 字符串12hello python itcast21被strip后,结果:hello python itcast
注意:传入的是“12” 其实就是:“1”和“2”都会移除,是按个单个字符。
- # 6. 统计字符串某个字符串的出现次数
- mystr = "itcast and it"
- count = mystr.count("it")
- print(f"字符串{mystr}it出现的次数:{count}")
-
- 字符串itcast and it,it出现的次数:2
- # 7. 统计字符串的长度
- num = len(mystr)
- print(f"字符串{mystr}的长度是,{num}")
-
- 字符串itcast and it的长度是,13
操作 | 说明 |
字符串[下标] | 根据下标索引取出特定位置字符 |
字符串.index(字符串) | 查找给定字符串的第一个匹配的下标 |
字符串.replace(字符串1,字符串2) | 将字符串1 替换为 字符串2 |
字符串.split(字符串) | 按照指定的分隔符字符串,将字符串划分为多个字符串,并存入列表对象中,得到的是一个列表 |
字符串.strip() 字符串.strip(字符串) | 移除首尾的空格和换行符或指定字符串 |
字符串.count | 统计字符串内某个字符串的出现次数 |
len(字符串) | 统计字符串的字符个数 |
同列表,元组一样也支持while,for循环进行遍历。
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。