Python数据容器(字符串)

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']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值