python--数据容器--str字符串

目录

字符串

字符串查找

字符串替换

字符串的分割

字符串的规整操作(去前后空格,只去字符串前后的,不去中间的)

字符串的规整操作(指定的字符串)

字符串遍历 ​编辑


字符串

尽管字符串看起来并不像:列表、元组那样,一看就是存放了许多数据的容器

但不可否认的是,字符串同样也是数据容器的一员

字符串是字符的容器。一个字符串可以存放任意数量的字符

和其他容器如:列表、元组一样,字符串也可以通过下标进行访问

从前向后,下标从0开始

从后向前,下标从-1开始


# 通过下标获取特定位置字符

name = "itheima"
print(name[0])  # 结果是 i
print(name[-1])  # 结果 a

字符串查找

index

字符串替换

语法:字符串.replace(字符串1,字符串2)

功能:将字符串内的全部: 字符串1,替换为字符串2

注意:不是修改字符串本身,而是得到了个新的字符串

字符串的分割

语法:字符串.split(分隔符字符串)

功能:按照指定的分割符字符串,将字符串划分为多个字符串,并存入列表对象

注意:字符串本身不变,而是得到了一个列表对象

字符串的规整操作(去前后空格,只去字符串前后的,不去中间的)

语法:字符串.strip()

字符串的规整操作(指定的字符串)

语法: 字符串.strip(字符串)

my_str.strip("12")

注意 传入的是“12”  其实就是: “1”和“2”都会移除 是按照单个字符

"""
    演示以数据容器的角色 学习字符串的相关操作
"""

my_str = "itheima and itcast"

# 通过下标索引取值
value  = my_str[2]
value2 = my_str[-16]
print(f"从字符串{my_str}取下标为2的元素,,值是:{value},取下标为-16 的元素,值是:{value2}")
# 字符串不支持修改
# my_str[2] = "H"


# index方法
value = my_str.index("and")
print(f"在字符串{my_str}中查找and,其起始下标是:{value}")

# replace方法

new_my_str = my_str.replace("it", "程序")

print(f"将字符串{my_str},进行替换后得到:{new_my_str}")

# split方法
my_str = "hello python itheima it"
my_str_list = my_str.split(" ")
print(f"将字符串{my_str}进行split切分后得到:{my_str_list},类型是{type(my_str_list)}")


# strip 方法
my_str = "   itheima and itcast   " #不传入参数 只去首尾空格
my_str_strip = my_str.strip()
print(my_str_strip)

my_str = "12itheima  and it cast21"

new_my_str = my_str.strip("12")
print(f"字符串{my_str}被strip('12')后结果是,:{new_my_str}")


# 统计字符串中某字符串的出现次数,   count

my_str = "hello python itheima it ti"
count = my_str.count("it")
print(f"字符串{my_str}中it 出现的次数是{count}")


#统计字符串的长度 len


num = len(my_str)
print(num)


从字符串itheima and itcast取下标为2的元素,,值是:h,取下标为-16 的元素,值是:h
在字符串itheima and itcast中查找and,其起始下标是:8
将字符串itheima and itcast,进行替换后得到:程序heima and 程序cast
将字符串hello python itheima it进行split切分后得到:['hello', 'python', 'itheima', 'it'],类型是<class 'list'>
itheima and itcast
字符串12itheima  and it cast21被strip('12')后结果是,:itheima  and it cast
字符串hello python itheima it ti中it 出现的次数是2
26

Process finished with exit code 0

字符串遍历 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值