數字
整形int
二進制: 0b\0B
八進制: 0o\0O
十六進制: 0x\0X
浮點型float
布爾型bool
複數complex
組
序列
字符串
- 有序的
- 可以通過序號訪問
正向和反向序號的不同
正向是0開始
反向是-1開始
- 可以通過序號訪問
- 切片功能
注意
“:”和留白的應用
s[:m]
s[m:]
… - 不可變的
>>> s = 'foobar'
>>> s[3] = 'x'
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
s[3] = 'x'
TypeError: 'str' object does not support item assignment
想完成替換,可以使用
切片方法:
>>> s = s[:3] + 'x' + s[4:]
>>> s
'fooxar'
函數:
>>> s = 'foobar'
>>> s = s.replace('b', 'x')
>>> s
'fooxar'
- 轉義字符:
一行太長需要換行:輸入‘\’後enter
>>> print('a\
... b\
... c')
abc
\t — tab
>>> print("a\tb")
a b
>>> print("a\141\x61")
aaa
>>> print("a\nb")
a
b
- r和R的作用:將\保留,保持原始字符串形式
print('foo\nbar')
print(r'foo\nbar')
print('foo\\bar')
print(R'foo\\bar')
- 字符串運算
'foo' * 4
'foo' * -4
- f-string
python3.6 介紹的一種新的字符串格式化方式比較兩組代碼
傳統:
>>> n = 20
>>> m = 25
>>> prod = n * m
>>> print('The product of', n, 'and', m, 'is', prod)
The product of 20 and 25 is 500
f-string:
>>> n = 20
>>> m = 25
>>> prod = n * m
>>> print(f'The product of {n} and {m} is {prod}')
The product of 20 and 25 is 500
列表(list)
- 有序的
- 元素可以通過序號訪問
- 切片功能
- 可變的
- 可以包含任意的對象
- 可以多維
元組(tuple)
- 單元素元組的注意事項
type((1)) - 整形
type((“hello”)) - 字符串
如何定義只有一個元素的元組? - (1,),可以使用type((1,))檢驗
如何定義一個空的元組? - (),可以使用type(())檢驗 - 有序的
- 不可變的
- 使用元組的好處
- 同等情況下處理速度比list快
- 對於整個生命週期不變的數據,防止被篡改
- 在字典裏可以用來定義不可變的部分(就是key)
集合(set)
- 無序,沒有索引,不能切片
- 不重複
- a,b = b,a
>>> a = 'foo'
>>> b = 'bar'
>>> a, b
('foo', 'bar')
>>># Magic time!
>>> a, b = b, a
>>> a, b
('bar', 'foo')
- 可改變
- frozenset不可改變
>>> x = frozenset(['foo', 'bar', 'baz'])
>>> x
frozenset({'foo', 'baz', 'bar'})
除了不可改變,其他和set一樣
字典(dict)
- key:value 鍵值對是最基本的概念
- 任何不可變的數據類型都可以作爲key
總結
有序 | 無序 | |
---|---|---|
可變 | 列表 | 集合、字典 |
不可變 | 字符串、元組 | 數字 |
如果有任何疑問、建議或者有相關問題的討論,歡迎留言或者直接給我email:[email protected]