序列结构:列表(list)、元组(tuple)、集合(set)、字典(dict)、字符串(str)
一.字符串(str)
1.创建
string1 = "字符串常量"
string2 = '字符串常量'
关于单双引号的使用
string1 = 'hello, "c"'
print(string1)
string2 = "hello, 'c'"
print(string2)
输出结果
2.访问元素
可通过索引值随机访问
string = "abcdef"
print(string[2])
输出结果
3.切片
切片:截取序列一部分的操作
对象名[起始值:终止值:步长]
[起始值,终止值)前闭后开
至少含一个冒号':'
对象名:要截取的对象
起始值:缺省默认为0
终止值:缺省默认取到最后一个元素
步长:缺省默认为1,若步长为负数,则反向截取
示例
string = 'abcdefg'
print("1."+string[0:3]) # 1.string[0]到string[2]
print("2."+string[2:]) # 2.string[2]到最后一个元素
print("3."+string[1:-1]) # 3.string[1]到倒数第二个个元素
print("4."+string[:]) # 4.遍历
print("5."+string[::-1]) # 5.反向遍历
print("6."+string[::2]) # 6.步长为2
print("7."+string[5:1]) # 7.默认步长为1
print("8."+string[5:1:-1]) # 8.string[5]到string[2]
输出结果
4.字符串常见操作
常用方法:find(),count(),replace(),split(),join(),strip()
检索与检查:find()、index()、count()、startswith()、endswith()
字符串分割为列表:split()、partition()、splitlines()
列表连接为字符串:join()
填充对齐:ljust()、rjust()、center()
删除对齐:lstrip()、rstrip、strip()
替换:replace()
类型判定:isX()
(1)字符串检索
find()、index()、count()、startswith()、endswith()
1.find()方法
①find()方法
主串.find("子串",起始索引值,终止索引值)
str.find(sub, _start, _end)
检查目标字符串中是否包含在主串中(查找子串)。如果在,返回开始的索引值;否则,返回-1。
起始索引值:缺省从头开始检索
终止索引值:缺省检索至尾
②rfind()方法
主串.rfind("子串",起始索引值,终止索引值)
从右端开始检查
2.index()方法
①index()方法
主串.index("子串",起始索引值,终止索引值)
str.index(sub, _start, _end)
与find()方法相同,只不过未找到目标字符串会抛出一个异常。
起始索引值:缺省从头开始检索
终止索引值:缺省检索至尾
②rindex()方法
主串.index("子串",起始索引值,终止索引值)
从右端开始检查
3.count()方法