python之数据容器str

74 阅读1分钟
  • 字符串也属于数据容器的一种
  • 字符串也是只读的,不可以通过下标修改
  • 字符串不可以存其他类型,长度不受限制
  1. 字符串通过下标索引查找元素,字符串[元素]。
tag = "peace and love"
print(tag[5]) #
print(tag[-2]) # v
  1. 字符串也可以通过index查找元素,字符串.index(元素)。
tag = "peace and love"
print(tag.index('a')) # 2
print(tag.index('and')) # 6
  1. 字符串的replace() 替换元素 字符串.replace(字符串1, 字符串2) 将字符串中的字符串1全部替换为字符串2 并返回新的字符串,原字符串是不会修改的。
tag = "peace and love"
tag2 = tag.replace("and", "|")
print(tag2) # peace | love
  1. 字符串分割,字符串.split(分割符字符串),将字符串用分割符分割为多个字符串,返回一个列表,原字符串不会修改。
tag = "peace and love"
tag2 = tag.split("and")
print(tag2) # ['peace ', ' love']
# 也可以使用空字符串分割
tag3 = tag.split(" ")
print(tag3) # ['peace', 'and', 'love']

5.字符串的规整操作,字符串.strip() 可以去除字符串的前后空格,字符串.strip()有一个可选参数,传入参数就会去除前后的指定字符,原字符串不会修改。

tag = "       peace and love      "
tag2 = tag.strip()
print(f"结果:{tag2}") # 结果:peace and love

tag = "斗鸡山上鸡斗"
tag2 = tag.strip("斗鸡")
print(tag2) # 山上

tag = "123454312"
tag2 = tag.strip("12")
print(tag2) # 34543

6.统计字符串某个字符出现的次数,字符串.count(元素)。

tag = "peace and love"
tag_count = tag.count('a')
print(tag_count) # 2
  1. 统计字符串的长度,len(字符串)。
tag = "peace and love"
tag_len = len(tag)
print(tag_len) # 14