基础知识(7)
文章目录
数据容器–字符串
字符串的定义:
-
字符串是字符的容器,一个字符串可以存放任意数量的字符。
例如:“nihao”
-
字符串和元组一样是无法修改
字符串的内容可以通过下标索引取得
-
从前向后,下标从0开始
-
从后向前,下标从-1开始
my_str = "nihao and mthgh"
# 通过下标索引取值
value = my_str[2]
value2 = my_str[-15]
print(f"从字符串{my_str}取下标为2的元素,值是:{value},取下标为-16的元素的值是:{value2}")
#从字符串nihao and mthgh取下标为2的元素,值是:h,取下标为-16的元素的值是:n
字符串常见操作:
-
查找特定字符串
-
字符串的替换
-
字符串的分割
-
字符串的规整操作
去前后的空格
去前后指定字符串
-
统计字符串中某字符串的出现次数
-
统计字符串的长度
-
字符串的遍历
1.查找特定字符串(index方法)
my_str = "nihao and mthgh"
value = my_str.index("and")
print(f"在字符串{my_str}中查找and,其下标是:{value}")
#在字符串nihao and mthgh中查找and,其下标是:6
2.字符串的替换(replace方法)
my_str = "nihao and mthgh"
new_my_str = my_str.replace("it","黑马")
print(f"替换后为:{new_my_str}")
#替换后为:nihao and mthgh
3.字符串的分割(strip方法)
my_str = "hello python nihao mthgh"
my_str_list = my_str.split(" ")
print(f"将字符串{my_str}进行splic切分后得到:{my_str_list},类型是:{type(my_str_list)}")
#将字符串hello python nihao mthgh进行splic切分后得到:['hello', 'python', 'nihao', 'mthgh'],类型是:<class 'list'>
4.字符串的规整操作
my_str = "hello python nihao mthgh"
my_str = " nihao and mthgh "
new_my_str = my_str.strip() #不传入参数,去除首尾空格
print(f"字符串{my_str}被strip后,结果是;{new_my_str}")
#字符串 nihao and mthgh 被strip后,结果是;nihao and mthgh
其他情况:
my_str = "12nihao and imthgh21"
new_my_str = my_str.strip("12")
print(f"字符串{my_str}被strip('12')后,结果是:{new_my_str}")
#字符串12nihao and imthgh21被strip('12')后,结果是:nihao and imthgh
5.统计字符串中某字符串的出现次数
my_str = "nihao and mthgh"
count = my_str.count("mt")
print(f"字符串{my_str}中it出现的次数是:{count}")
#字符串nihao and mthgh中it出现的次数是:1
6.统计字符串的长度
my_str = "nihao and mthgh"
num = len(my_str)
print(f"字符串{my_str}的长度是:{num}")
#字符串nihao and mthgh的长度是:15
7.字符串的遍历
my_str = "明天会更好"
index = 0
while index <len(my_str):
print(my_str[index])
index += 1
#明
#天
#会
#更
#好