4-Python的序列类型

Python的序列类型

字符串的定义(str)

在最外层的单/双引号包裹内可以输入任何内容

注意:1. 单/双引号需要一一对应

           2. 三引号之间可以换行,一般还用来做注释

>>> a = 'qwe 123 !@# 你好 我好 “大家好” '

>>> a

'qwe 123 !@# 你好 我好 “大家好” '

>>> b = "qwe 123 !@# 你好 我好 '大家好' "

>>> b

"qwe 123 !@# 你好 我好 '大家好' "

>>> c = """ 

... 123 

... qwe 

... 你好""" 

>>> print(c) 

123 

qwe     

你好    

>>> type(a) 

<class 'str'> 

>>> type(b) 

<class 'str'> 

>>> type(c) 

<class 'str'>

列表的定义(list)

列表是可迭代的对象,通常是用中括号包裹,里面使用逗号隔开.

>>> li = [1, 2, 3, 'qwe']

>>> type(li) 

<class 'list'>  

元组的定义(tuple)

元组是可迭代对象,通常是用小括号包裹,里面使用逗号隔开

注意:1. 只有一个元素时,需要在这个元素的末尾加上逗号

           2. 有时不加小括号也可以定义一个元组, python会自动加上小括号

>>> tu = (1, 2, 3) 

>>> tu1 = (1,) 

>>> type(tu) 

<class 'tuple'> 

>>> type(tu1) 

<class 'tuple'>     

>>> tu2 = 1, 2, 3 

>>> type(tu2)

<class 'tuple'>  

1. 对于列表和元组来说,要怎么样才能取到里面的值呢?

我们可以使用索引和切片的方式来取一个或多个的值

注意:1. 不管索引还是切片都是从0号位置开始数的

           2. 超出索引的范围会报错IndexError: list/tuple index out of range

           3. 切片规则:左闭右开(包前不包后)

           4. 切片还有一个默认步长li[xx:xx:步长],步长默认是1

           5. 反向切片的时候注意要将步长变为负数

           6. 切片和索引还适用于字符串和整型

#    索引

>>> li = [1, 2, 3, 'qwe', (4, 5, 6)] 

>>> li[0]

 1 

>>> li[1] 

>>> li[2]      

>>> li[3] 

'qwe' 

>>> li[4] 

(4, 5, 6) 

>>> li[4][1]  

>>> li[4][0] 

>>> li[4][2]         

6   

#    切片

>>> li = [1, 2, 3, 'qwe', (4, 5, 6)] 

>>> li[0:] 

[1, 2, 3, 'qwe', (4, 5, 6)]  

>>> li[:5] 

[1, 2, 3, 'qwe', (4, 5, 6)] 

>>> li[-1:-5:-1] 

[(4, 5, 6), 'qwe', 3, 2] 

类型转换

>>> li = [1, 2, 3, 'qwe', (4, 5, 6)]

>>> tuple(li)

(1, 2, 3, 'qwe', (4, 5, 6))

>>> list(tu)

[4, 5, 6]

>>> str(li)

"[1, 2, 3, 'qwe', (4, 5, 6)]"

bytes二进制序列类型

注意:bytes是python3中特有的,python2中不区分str和bytes

>>> bytes(b'abc')        #    指定长度的零填充字节对象

b'abc'

>>>bytes(10)           #    二进制字符串对象

b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 

bytearray二进制数组

>>>bytearray(10)         #    指定长度的零填充字节对象

bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

>>> bytearray(b'abc')       #    二进制字符串对象

bytearray(b'abc')    


英文汇总

class

tuple

list

str

int

Index

Error 

python

out

of 

range  

bytes

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。