python中常用的序列结构有哪些_Python序列结构

序列结构:列表(list)、元组(tuple)、集合(set)、字典(dict)、字符串(str)一.字符串(str)1.创建string1 = "字符串常量"string2 = '字符串常量'关于单双引号的使用string1 = 'hello, "c"'print(string1)string2 = "hello, 'c'"print(string2)输出结果2.访问元素可通过索引值随机访问st...
摘要由CSDN通过智能技术生成

序列结构:列表(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()方法

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值