数据容器-str-Python

师从黑马程序员

字符串的定义和操作

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

my_str="itheima and itcast"

value=my_str[2]
value2=my_str[-16]
print(f"从字符串中{my_str}取下标为2的元素:值是:{value},取下标为-16的元素,值是:{value2}")

均无法完成,如果必须要做,就只能得到一个新的字符串,旧的字符串是无法修改的

查找字符串的下标索引值

my_str="itheima and itcast"

value=my_str.index("and")
print(f"and在my_str中的起始坐标为:{value}")

字符串的替换

my_str="itheima and itcast"

new_my_str=my_str.replace("it","程序")
print(f"{my_str}替换后的字符串为:{new_my_str}")

字符串的分割

my_str="itheima and itcast"

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

 字符串的规整操作(去前后空格)

my_str="  itheima and itcast  "

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

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

计算特定字符串出现的次数

my_str="itheima and itcast"

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

统计字符串的长度

my_str="itheima and itcast"

num=len(my_str)
print(f"字符串{my_str}的长度是:{num}")

总结 

字符串的遍历

my_str="黑马程序员"
index=0
while index<len(my_str):
    print(my_str[index])
    index+=1

my_str="黑马程序员"
for i in my_str:
    print(i)

典型案例:

my_str = "itheima itcast boxuegu"

count = my_str.count("it")
print(f"字符串{my_str}中有{count}个'it'")

# 将 'i' 替换为 'l'
replace_str = my_str.replace("i", "l")
print(f"字符串{my_str}被将'i'替换为'l'后,结果:{replace_str}")

# 按照 'l' 分割字符串(这里假设我们已经将 'i' 替换为了 'l')
split_list = replace_str.split("l")
print(f"字符串{replace_str}按照'l'分割后,得到:{split_list}")

若有侵权,请联系作者

相关推荐

  1. Python数据容器(上)——list(列表)

    2024-03-22 07:36:05       26 阅读
  2. Python基础----数据容器(持续更新中)

    2024-03-22 07:36:05       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-22 07:36:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-22 07:36:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-22 07:36:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-22 07:36:05       20 阅读

热门阅读

  1. 关于Windows 10 LTSC 2019无法安装Edge的解决方案

    2024-03-22 07:36:05       34 阅读
  2. macOS 合并同名文件夹 按住 Option 键

    2024-03-22 07:36:05       18 阅读
  3. React核心⼊⻔-lesson1

    2024-03-22 07:36:05       18 阅读
  4. 2024.3.21 ARM

    2024-03-22 07:36:05       20 阅读
  5. C++ 函数指针与回调函数

    2024-03-22 07:36:05       24 阅读
  6. 全球化战略中的技术纵深

    2024-03-22 07:36:05       19 阅读
  7. android11 系统的启动流程 的面试题目

    2024-03-22 07:36:05       21 阅读