一、常见的字符串操作符:+、*、in
+和*的简单应用:
s1 = "Hello"
s2 = "World"
print(s1+s2)
print(s1*3)
in的简单应用:
s1 = "How are you doing?"
print("are" in s1)
s1 = "How are you doing?"
print("are" in s1)
print("aa" in s1)
s2 = "yo"
print(s2 in s1)
二、字符串索引和切片
1.字符串索引
·索引用来表示字符串中字符的所在位置
·基于位置,可以快速找到其对应的字符
·如果一个字符串中有n个字符,那么索引的取值范围是0~n-1
语法:
<字符串或字符串变量>[索引]
#字符串索引
s = "How are you doing?"
print(s[0]) #输出H
2.字符串切片
·使用切片可以获取字符串指定索引区间的字符
语法:
<字符串或字符串变量>[开始索引:结束索引:步长]
#字符串切片
s = "How are you doing?"
print(s[1:6])#表示从字符串s中取出第1个位置到第6个位置的字符串,不包含结束索引的位置(第6个位置的字符)
print(s[1:])#从字符串s中取第1个位置到最后的字符
print(s[:8])#从字符串s中取第0个位置到第8个位置的字符,不包含第8个位置的字符
print(s[:])#取全部
#步长,不太常用
s = "How are you doing?"
print(s[0:11])
print(s[0:11:1])#步长为1,是只从第0个位置开始,每挨着一位取一个。
print(s[0:11:2])#步长为2,每两个取一个。
print(s[::-1])#整体进行一个逆序排列
s = "abcdefghijklmn"
print(s[::-1])
print(s[-1])#指倒数第一位
print(s[-2])
print(s[:-2])