php如何做网站,知名网站制作服务,北京企业网络推广外包,百度优化培训字符串 1.字符串 字符串也是数据容器的一种#xff0c;字符串是字符的容器#xff0c;一个字符串可以存放任意数量的字符。 2.字符串的下标索引
从前向后#xff0c;下标从0开始从后向前#xff0c;下标从-1开始
# 通过下标索引获取特定位置的字符
name python
print(na… 字符串 1.字符串 字符串也是数据容器的一种字符串是字符的容器一个字符串可以存放任意数量的字符。 2.字符串的下标索引
从前向后下标从0开始从后向前下标从-1开始
# 通过下标索引获取特定位置的字符
name python
print(name[0]) # 结果 p
print(name[-1]) # 结果 n同元组一样字符串也是一个无法修改的数据容器
3.字符串的常用操作
查找特定字符串的下标索引值 语法字符串.index(字符串)
my_str itcat and itheima
print(my_str.index(and)) # 输出 6字符串的替换 语法字符串.replace字符串1字符串2功能将字符串内的全部字符串1替换为字符串2注意不是修改字符串本身而是得到一个新的字符串
name itcat and itheima
new_name name.replace(it,传智)
print(new_name) #结果 传智cat and 传智heima
print(name) # 结果 itcat and itheima字符串的分割 语法字符串.split(分割字符串)功能按照指定的分隔符字符串将字符串划分为多个字符串并存入列表中注意字符串本身不变而是得到一个新的列表对象
name itcat and itheima
new_name name.split( )
print(new_name) # 结果 [itcat, and, itheima]字符串的规整操作(去前后空格) 语法字符串.strip()
name itcat and itheima
new_name name.strip()
print(new_name) # 结果 itcat and itheima字符串嗯对规整操作去前后指定字符串 语法字符串.strip字符串
name 12itcat and itheima21
new_name name.strip(12)
print(new_name) # 结果 itcat and itheima统计字符串中某字符串的出现次数 语法字符串.count(字符串)
name itcat and itheima
num name.count(it)
print(num) # 结果 2统计字符串的长度 语法len(字符串)
name itcat and itheima
print(len(name)) # 结果 17编号操作1字符串[下标索引]根据索引取出特定位置的字符2字符串.index(字符串)查找给定字符的第一个匹配项的下标3字符串.replace(字符串1字符串2)将字符串内的全部字符串1替换为字符出串2不会修改原字符串而是得到一个新的4字符串.split(字符串)按照给定的字符串对字符串进行分隔不会修改原字符串而是得到一个新的列表5字符串.strip()字符串.strip(字符串)移除首尾的空格核换行符或指定字符串6字符串.count(字符串)统计字符串内某字符串的出现的次数7len(字符串)统计字符串的字符个数
4.字符串的遍历
while遍历
my_str 程序员
index 0
while index len(my_str):print(my_str[index])index 1 # 结果 程序员for遍历
my_str 程序员
for element in my_str:print(element) # 结果 程序员5.字符串的特点
只可以存储字符串长度任意取决于内存大小支持下标索引允许重复字符串存在不可以修改增加或修改元素支持while、for循环
6.练习
# 定义一个字符串
my_str itheima itcast boxuegu
# 统计字符串内有多少个it字符
print(f字符串{my_str}中有{my_str.count(it)}个it字符)
# 将字符串内的空格全部替换为字符“|”
print(f字符串{my_str},被替换空格后结果{my_str.replace( ,|)})
# 并按照“|”进行字符分割的带列表
new_str my_str.replace( ,|)
new_str2 new_str.split(|)
print(f字符串{new_str},按照|分隔后得到{new_str2})
## 输出
字符串itheima itcast boxuegu中有2个it字符
字符串itheima itcast boxuegu,被替换空格后结果itheima|itcast|boxuegu
字符串itheima|itcast|boxuegu,按照|分隔后得到[itheima, itcast, boxuegu]