python之基本语法【字符 串切片】
字符串的下标,从0开始的(从前往后),从-1开始(从后往前数)
1.切片
str = "pyton hello"
print("str[2]=", str[2])
print("str[-2]=", str[-2])
# 字符串的切片操作,【起始位置:终止位置】:去头不取尾,虫开始位置开始,到终止位置的前一个
str2 = str[0:10]
print("str2=", str2)
# [起始位置:终止位置:步长”]:步长为多少,就是多少个去第一个
st2="1234567890"
print("str2[::2]==",st2[::2])
打印结果
str[2]= t str[-2]= l str2= pyton hell str2[::2]== 13579
2.字符串拼接
1)第一种是使用:+
2)第二种是使用jion
字符串X:jion(字符串1,字符串2,字符串3.......):字符串1 字符串x字符串2字符串x字符串3字符串x.....
str = "pyton hello" str2="1234567890" print("str.join(st2)===",str.join(str2)) print("','.join(str1,str2)===",','.join((str,str2))) str3="asdfghjkl" print("str3.join((str,str2))===",str3.join((str,str2))) str4="zxcvbnm" print("str3.join((str,str2,str4))===",str3.join((str,str2,str4)))
打印结果:
str.join(st2)=== 1pyton hello2pyton hello3pyton hello4pyton hello5pyton hello6pyton hello7pyton hello8pyton hello9pyton hello0 ','.join(str1,str2)=== pyton hello,1234567890 str3.join((str,str2))=== pyton helloasdfghjkl1234567890 str3.join((str,str2,str4))=== pyton helloasdfghjkl1234567890asdfghjklzxcvbnm
3.字符串转移
1)\n:换行符
2)\t:制表符,不足4位自动补齐四位
print("7777\n8888\n99999")
print("7777\t8888\t99999")
打印结果
7777
8888
99999
7777 8888 99999
注意:不想转义,在字符串前加小写r
4.字符串的方法
方法的调用格式:字符串.方法名()
1)find:查找字符串片在字符串中的下标位置(起始位置)
不存在字符串片段返回-1
str='qwertwyuiop' print(str.find("ert")) print(str.find("erm")) print(str.find("w")) #从前往后找,返回的是一个被找到字符串片段的起始位置 print(str.find("w",2)) print(str.find("w",3)) 打印结果 2 -1 1 5 5
2)count:统计字符串片段在字符串中出现的次数
注意:字符串片段不存在返回0
str='qwertwyuiop' print(str.count("w")) print(str.count("a")) 打印结果 2 0
3)replace:替换指定字符串片段
参数1:要替换的字符串片段
参数2:被替换之后的字符串片段
参数3:指定替换的次数(默认替换所有的)
str='qwertwyuiop' print(str.replace("w","W")) print(str.replace("w","W",1)) 打印结果 qWertWyuiop qWertwyuiop
# [起始位置:终止位置:步长”]:步长为多少,就是多少个去第一个
st2="1234567890"
print("str2[::2]==",st2[::2])