變量
變量代表內(nèi)存中的一個位置,可以是數(shù)據(jù)、對象、方法等
Python中的變量沒有類型,不需要單獨聲明,直接等號賦值即可,如a=100
變量名稱遵循標(biāo)識符規(guī)范
多個變量可以連續(xù)賦相同值,如a=b=c=100相當(dāng)于abc分別等于100
多個變量可以同時賦予不同值,如a,b=100,'hello'相當(dāng)于a=100和b='hello'
>>> a,b = 1,3
>>> a,b
(1, 3)
>>> a,b = b,b+1
>>> a,b
(3, 4)
查看數(shù)據(jù)類型
用type()和isinstance()方法查看數(shù)據(jù)類型,區(qū)別是type是最底層子類,isinstance是父類。
>>> a='hello'
>>> type(a)
<class 'str'>
>>> type(a)==str
True
>>> isinstance(a,str)
True
>>> a=True #布爾值是int的子類
>>> type(a)
<class 'bool'>
>>> isinstance(a,int)
True
>>> isinstance(a,float)
False
刪除數(shù)據(jù)
del命令可以刪除變量,實際上只是刪除引用,內(nèi)存中的數(shù)據(jù)會被自動回收
>>> c=100
>>> c
100
>>> del c
>>> c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
標(biāo)準(zhǔn)數(shù)據(jù)類型
Number(數(shù)字)
String(字符串)
List(列表)
Tuple(元組)
Set(集合)
Dictionary(字典)
其中Number和String是基本數(shù)據(jù)類型,List、Tuple、Set、Dictionary是容器類型
Number數(shù)字
Python3 數(shù)字支持 int整數(shù)(包含bool布爾)、float浮點數(shù)(小數(shù))、complex復(fù)數(shù)
bool只有True和Flase兩個值,相當(dāng)于1和0
復(fù)數(shù)由real實部和imag虛部兩個浮點數(shù)組成,100+2.1j格式,如果只有虛部,則實部為0,如c=200j,J不分大小寫
系統(tǒng)中float小數(shù)的精度可以使用sys.float_info查看;
Python3支持不同類型數(shù)字之間的直接計算,其中會把范圍較窄的轉(zhuǎn)換為較寬的類型,寬窄依次是complex>float>int
>>> a=True
>>> b=30
>>> a+b
31
>>> a=10
>>> b=0.2
>>> a+b
10.2
數(shù)字之間可以相互轉(zhuǎn)換,int(),float(),complex()方法,注意復(fù)數(shù)必須分開real或imag部分單獨轉(zhuǎn)換
>>> int(10.2)
10
>>> c=100+20j
>>> int(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to int
>>> float(c.real)
100.0
int('x', base=10),base可以使用二進(jìn)制0b、八進(jìn)制0o、十六進(jìn)制0x表示
>>> a=int('011',8)
>>> a
9
>>> a=0b11
>>> a
3
>>> a=0o11
>>> a
9
>>> a=0x11
>>> a
17
Python 2整數(shù)范圍可以用sys.maxsize查看,但實際上python3允許使用任意大小的整數(shù)。
>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
float('inf')表示無限大的浮點數(shù),float('-inf')表示無限小
浮點小數(shù)按精度截取使用round(10/3,3)截取三位3.333;math.ceil較大整數(shù),floor取較小整數(shù)。
>>> import math
>>> math.ceil(10/3)
4
>>> math.floor(10/3)
3
String字符串
使用單引號、雙引號或者三個引號包裹的文本內(nèi)容
'allows embedded "double" quotes'
"allows embedded 'single' quotes"
'''Three single quotes'''
"""Three double quotes"""
特殊字符可以用反斜杠轉(zhuǎn)義,如\n表示回車,'表示單引號,"表示雙引號,需要print輸出時候會被轉(zhuǎn)義
>>> s='A\nB\'C\"d'
>>> print(s)
A
B'C"d
三個引號支持多行文本,也可用于注釋內(nèi)容
>>> '''
... AAA
... BBB
... '''
'\nAAA\nBBB\n'
如果需要把長內(nèi)容換行輸入,可以使用()方法如下:
>>> s=('ab' 'c')
>>> s
'abc'
>>> s=('a'
... 'bc')
>>> s
'abc'
Python沒有表示單個字符的類型,字符串可以索引獲得單個字符,但不能通過索引進(jìn)行修改
>>> s='abcde'
>>> s[0],s[:2],s[2:],s[1:3]
('a', 'ab', 'cde', 'bc')
>>> s[2]='x'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Python3字符串默認(rèn)uft-8編碼str(object=b'', encoding='utf-8', errors='strict')
以b開頭的字符串返回一個字節(jié)byte類型,以r開頭的字符串禁止轉(zhuǎn)義(多用于正則表達(dá)式),以u開頭的字符串與默認(rèn)utf8編碼一致,u可省略
>>> b=b'abc'
>>> b
b'abc'
>>> s=r'A\nB'
>>> print(s)
A\nB
以f開頭的字符串表示字符串中{}內(nèi)用相應(yīng)的變量替換,和format方法作用很像
>>> weight=100
>>> s=f'wei:{weight}'
>>> s
'wei:100'
>>> s='weight:{w}'.format(w=weight)
>>> s
'weight:100'
>>> height=90
>>> s='wei:{1},hei:{0}'.format(height,weight)
>>> s
'wei:100,hei:90'
>>> s='ratial:{:}'.format(10/3)
>>> s
'ratial:3.3333333333333335'
>>> s='ratial:{:.5}'.format(100/3) #保留共5位數(shù)字
>>> s
'ratial:33.333'
更多format示例:
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."
>>> f"He said his name is {repr(name)}." # repr() 等同 !r
"He said his name is 'Fred'."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # 嵌套
'result: 12.35'
>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # 使用date數(shù)據(jù)格式化標(biāo)準(zhǔn)
'January 27, 2017'
>>> number = 1024
>>> f"{number:#0x}" # 指定16進(jìn)制
'0x400'
在print方法中,可以結(jié)合%進(jìn)行變量替換
>>> a='ABC'
>>> print('a is %s' % a) #這里的%s的s是string,表示是個字符串變量,如果是數(shù)字則%d
a is ABC
str.join(iterable)可用于連接可枚舉對象如list
>>> li=['a','b','c']
>>> '-'.join(li)
'a-b-c'
lstrip()移除左側(cè)空白字符,rstrip()移除右側(cè)空白字符,strip()兩端同時移除
>>> s='\n ABC'.lstrip()
>>> s
'ABC'
str.lower()全部轉(zhuǎn)小寫,str.upper()轉(zhuǎn)大寫
str.replace(old, new[, count])替換字符,count表示替換總數(shù)??梢杂脕韯h除某些字符。
>>> s='abc123'
>>> s.replace('bc','BC')
'aBC123'
>>> s.replace('12','')
'abc3'
如果要特殊替換的話需要使用正則表達(dá)式,例如替換非數(shù)字內(nèi)容:
>>> p=re.compile('[^0-9]{1}')
>>> re.sub(p,'-',s)
'---123'
index和find用來查找字符串中特定字符,找到則返回位置,否則index報錯而find返回-1;in可以直接判斷是否存在
>>> s='abc123'
>>> s.find('2')
4
>>> s.rfind('2')
4
>>> s.index('2')
4
>>> '2' in s
True
tr.split(sep=None, maxsplit=-1)用于將字符串切割成列表,例如:
>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
str.zfill()為數(shù)字填充空位0
>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'
加法符號可以把字符串相加,乘法符號*用來表示重復(fù)字符的個數(shù)
>>> s='A'*5
>>> s
'AAAAA'
bytes字節(jié)
字節(jié)是二進(jìn)制的數(shù)據(jù),可以用bytes方法生成,也可以用b加字符串格式
>>> b=b'hello'
>>> b
b'hello'
>>> b=bytes('hello','ascii')
>>> b
b'hello'
由于字符串默認(rèn)用ascii編碼模式,所以并不支持中文。使用'utf8'或'gbk'編碼可支持中文
>>> b=b'你好'
File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> b=bytes('你好','ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
>>> b=bytes('你好','utf8')
>>> b
b'\xe4\xbd\xa0\xe5\xa5\xbd'
字節(jié)和字符串轉(zhuǎn)換用encode和decode,但要注意編碼和解碼格式要一致
>>> s='你好'
>>> s.encode()
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> s.encode(encoding='utf8')
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> s.encode(encoding='ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
None
空值,它不是任何值
>>> a=None
>>> a==False
False
Python沒有undefined類型,對于不確定情況只能try...except嘗試
del k
try:
k
except NameError:
print('set to None')
k=None
print(k)
輸出
set to None
None