字符串是字符的容器,一个字符串可以存放任意数量的字符,只可以存储字符串,可使用下标索引,同样可遍历。
同元组一样,是一个无法修改的数据容器。修改、移除、追加指定字符等操作均无法完成,如果必须进行此类操作,只会得到一个新的字符串,旧的字符串无法修改。
# 字符串的特点
作为数据容器,字符串有如下特点:
1、只可以存储字符串
2、长度任意(取决于内存大小)
3、支持下标索引
4、允许重复字符串存在
5、不可以修改(增加或删除元素等)
6、支持for循环
# 01 字符串[下标]:根据下标索引取出特定位置字符
my_str = "xiao man 77"
value1 = my_str[3]
value2 = my_str[-1]
print(value1, value2) # o 7
# 02 字符串.index(字符串):查找给定字符的第一个匹配项的下标
my_str = "xiao man 77"
value1 = my_str[3]
value2 = my_str[-1]
print(value1, value2) # o 7
# 03 字符串的替换
语法:字符串.replace(字符串1,字符串2)
功能:将字符串内的全部:字符串1,替换为字符串2
注意:不是修改字符串本身,而是得到了一个新的字符串
my_str="明日出来的风"
new_my_str = my_str.replace("明日出来的风", "强风吹拂")
print(new_my_str) # 强风吹拂
# 04 字符串的分割
语法:字符串.split(分隔符字符串)
功能:按照指定的分隔符字符串,将字符串划分为多个字符串,并列入列表对象中
注意:字符串本身不变,而是得到了一个列表对象
my_str1="hello world go to it"
my_str2="god,is,a,girl"
my_str_1=my_str1.split(" ") # 这次是使用空格进行分隔
my_str_2=my_str2.split(",") # 这次是使用英文下逗号分隔进行分隔
print(my_str_1)# ['hello', 'world', 'go', 'to', 'it']
print(type(my_str_1)) # <class 'list'>
print(my_str_2)# ['god', 'is', 'a', 'girl']
print(type(my_str_2)) # <class 'list'>
# 05 字符串的规整操作(去前后空格)
##语法:字符串.strip(),去字符串首尾空格
my_str = " hello michiko san "
new_my_str = my_str.strip()
print(new_my_str)
## 语法:字符串.strip(字符串),去前后指定字符串
## 注意:只会移除首尾的“7334”,是按照单个“7”,“3”,“4”来移除。
my_str= "734day 734hello michiko san6448734734"
new_my_str1 = my_str.strip("734")
print(new_my_str1) # day 734hello michiko san6448
# 06 字符串.count(字符串):统计字符串内某字符串的出现次数
my_str_3 = "ai xiao ba ma ka ba ka"
count = my_str_3.count("ba")
print(count) # 2
# 07 len(字符串):统计字符串的字符个数。
lenth = len(my_str_3)
print(lenth) #22 16+6个空格
# 字符串的遍历
##同列表、元组一样,字符串也支持while和for循环进行遍历
# while循环
my_list_1="王牌对王牌"
index=0
while index<len(my_list_1):
print(my_list_1[index])
index +=1
# for 循环
my_list_2="中国欢乐行"
for i in my_list_2:
print(i)
'''
运行结果:
王
牌
对
王
牌
中
国
欢
乐
行
进程已结束,退出代码为 0
'''
# 练习案例:分隔字符串
给定一个字符串:"itheima itcast boxuegu"
· 统计字符串内有多少个‘it“字符
·将字符串内的空格,全部替换为字符:”|“
· 并按照”|“进行字符串分割,得到列表
str_1="itheima itcast boxuegu"
count= count=str_1.count("it")
print(f"字符串{str_1}中有it字符串的个数:{count}") # 字符串itheima itcast boxuegu中有it字符串的个数:2
replace_str=str_1.replace(" ","|")
print(f"字符串{str_1}中替换空格符后为:{replace_str}") # 字符串itheima itcast boxuegu中替换空格符后为:itheima|itcast|boxuegu
str_2=replace_str.split("|")
print(f"字符串{replace_str} 进行分割后得到一个列表:{str_2}") # 字符串itheima|itcast|boxuegu 进行分割后得到一个列表:['itheima', 'itcast', 'boxuegu']