字符串是 Python 中最常用的数据类型。我们可以使用引号 ( ’ 或 " ) 来创建字符串。
# 字符串
# 通过下标索引取值
mystr = "abcdefgh"
value = mystr[2]
print(f"获取下标为2的元素{value}")
# index()方法
values = mystr.index("c")
print(f"字符串中c的下标为{values}")
# replace()方法
newstr = mystr.replace("c", "a")
print(f"替换后的字符串{newstr}")
# split()方法
my_str = "a,b,c,d,e,f,g,h"
spstr = my_str.split(",")
print(f"切割后{spstr}")
# strip()方法 不传参数去除前后空格
my_strs = " abcdefgh "
newmy_strs = my_strs.strip()
print(F"字符串strip后是:{newmy_strs}")
my_strs1 = "32abcdefgh23"
newmy_strs1 = my_strs1.strip("23")
print(F"字符串strip传参后是:{newmy_strs1}")
# 统计字符串中某个字符穿线的次数
my_strs2 = "abcdefgha"
count = my_strs2.count("a")
print(f"字符串a出现次数{count}")
# 统计字符串的长度
num = len(my_strs2)
print(f"字符串长度是:{num}")
运行结果:
获取下标为2的元素c
字符串中c的下标为2
替换后的字符串abadefgh
切割后[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’]
字符串strip后是:abcdefgh
字符串strip传参后是:abcdefgh
字符串a出现次数2
字符串长度是:9