python基础:字符串常用操作汇总

通过下标取值

my_str = "%pokes$@163&.com*"
value1 = my_str[2]  # 正向下标从0开始
value2 = my_str[-5]  # 反向下标从-1开始

print(value1)   #运行结果是“o”
print(value2)   #运行结果是“.”

index方法:查找特定字符串的下标索引值

my_str = "%pokes$@163&.com*"
value3 = my_str.index("pokes")
print(value3)   

#运行结果是“1”
注意:1"pokes"起始下标,即p所在的下标位置

replace方法:字符串替换

str2= "ithahahaaa and ithehehehe"
new_str2 = str2.replace("it","pokes")    #将it替换成pokes
print(new_str2)        

#运行结果:pokeshahahaaa and pokeshehehehe

split方法:分割字符串

str3= "abc-123-C-爱丽丝-遥远的故事.pdf"
new_str3 = str3.split(".")
print(new_str3)
new_str4 = str3.split("-")
print(new_str4)

运行结果:
在这里插入图片描述

strip方法:去除字符串两端的空格和回车符

注意不包含中间的空格

str5= "     heihei hehe haha    "
new_str5=str5.strip()   #不传参数,默认去除两端的空格和回车符
print(new_str5)

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

str6= "heihei hehe haha"
cishu = str6.count("he")
print(cishu)

#运行结果:4

len统计字符串的长度

str6= "heihei hehe haha"
num=len(str6)
print(num)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/annita2019/article/details/130015769