Python 的內建物件

2022-08-03 14:57:14 字數 2098 閱讀 1735

python中一切皆是物件,主要的內建物件有:1. 數字(整型int、浮點型float)2. 字串(不可變性) 3.列表 4.字典 5.元組(不可變性) 6.檔案 7.集合(不重複性)

數字支援+-*/運算,有強大的math模組

>>> round(3.1415926,2)

3.14(保留小數點位數)

>>> num = '%.2f' %3.1414596

>>> num

'3.14'(字串格式化,輸出為字串)

字串:切片、索引、查詢、替換、格式化,迴圈

>>> 'ming'[2] 索引

'n'>>> 'ming'.index('n') 索引

2>>> 'ming'.find('n')查詢還可以用re模組

2>>> 'ming'.replace('n','m')替換修改字串的乙個方法

'mimg'

>>> 'i am %s and %d years old' %('ming',18)字串的格式化

'i am ming and 18 years old'

>>> 'ming'[::-1]

'gnim'  反轉功能

列表:切片、索引、迴圈、追加

>>> l

['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey', ['nihao', 'hao']]

>>> l.sort()   巢狀列表不支援排序

traceback (most recent call last):

file "", line 1, in

l.sort()

typeerror: '<' not supported between instances of 'list' and 'str'

>>> l

['hah', 'hello', 'hey', 'i', 'l', 'l', 'lily', 'ming', 'python', 'world', 'y', ['nihao', 'hao']]

>>> l=['l','h','i']

>>> l.sort()

>>> l

['h', 'i', 'l']

>>> l.reverse() 取反

>>> l

['l', 'i', 'h'] 

字典:對映、巢狀、迴圈、排序

>>> dict =

>>> dict['li'] 對映

'nanjing'

>>> dict['jim'] = 'shenzhne' 填充字典

>>> dict

>>> l = list(dict.keys()) 獲取字典的鍵

>>> l

['ming', 'li', 'lucy', 'jim']

>>> l.sort() 排序

>>> l

['jim', 'li', 'lucy', 'ming']

>>> for each in l: 格式化輸出

print(each,dict[each])

jim shenzhne

li nanjing

lucy shanghai

ming hangzhou

>>> dict

>>> value = dict.get('good','moring')字典的查詢get方法,沒有則返回預設值而不報錯

>>> value

'moring'

>>> dict

>>>

元組:乙個不可變的列表

集合:不重複性 支援集合運算

>>> a =

>>> b =

>>> a&b交集

>>> a|b並集

>>> a-b a中有b中沒有

>>> b-a b中有a中沒有

>>> a^b ab交集中沒有的

>>>

Python的內建物件

python的內建物件 物件型別 型別名稱 簡要說明 數字int,float,complex 支援任意大的數字,具體程度受記憶體的限制 字串str python中沒有字元常量和字元變數,只有字串常量和變數 位元組串bytes 以字母b引導,如b hello world 列表list 所有元素在 方括...

Python 內建物件

方法 功能bit length 返回以二進位制表示乙個整數所需要的位數,不包括符號位和前面的零 to bytes length,byteorder,signed false 返回表示乙個整數的位元組陣列 from bytes bytes,byteorder,signed false 返回由給定位元組...

python內建物件型別

python內建物件型別 有 數字,字串,列表,元組,字典,集合等 pickle醃製 為了達到對一些物件進行持久化的儲存,並且不丟這個物件的型別與資料,我需要對這個物件進行序列號,然後存在記憶體或者存在第三方檔案,然後序列號的過程就叫醃製 例項 import pickle 匯入模組 lista na...