Python3 中有六個標準的數據類型:python
str.__doc__:git
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.api
索引對應元素的位置app
示例:dom
>>> string = 'hello world!' >>> print(string[1]) # 正序從0開始 到最後 第一個字符的索引值爲 0 第二個爲 1 e >>> string = 'hello world!' >>> string[0] 'h' >>> string[-1] # 逆序索引 最後一個索引值爲 -1 從後往前 依次爲 -一、-二、-3 … '!’ >>> string[0:6] #切片 string[起始索引:終止索引] 獲得的是新的字符串 'hello ' >>> string[0:] #不寫終止索引,即爲取到最後 'hello world!' >>> string[4:] 'o world!' >>> string[:] # 都不寫 就是全切片 從[:-1] 'hello world!' >>> string[::-1] # 終止索引後的參數爲 步長 string[起始索引:終止索引:步長] 全切片 而後逆序 步長爲負 從從後往前 每次取1個 '!dlrow olleh' >>> string[::2] # 步長爲2 從前日後 隔一個取一個 'hlowrd'
注意:切片以後的結果是對原字符串的部分絕對拷貝(深拷貝),便是兩個徹底獨立的對象,而不是淺拷貝或者對原對象的部分引用。函數
在Python中格式化迄今爲止一共有四種方法 最先期的「%」方法,後來的format()方法,和3.6版本出現的f-string方法,以及模塊處理方法ui
用法:'***%s**'%(var) #var的值會填充到%s的位置 組成新的字符串編碼
示例:spa
>>>」name :%s age :%d birthday :%s"%('monkey',20,'2010-10-20') >>>name :monkey age :20 birthday :2019-10-20
其中 %s 稱爲佔位符,在字符串的後面緊跟 %和變量 若是佔位符大於一個,要在%後以元組的形式傳入替換的變量經常使用的佔位符:
code
%s 字符串
%c 字符
%d 十進制(整數)
%i 整數
%u 無符號整數
%o 八進制整數
%x 十六進制整數
%X 十六進制整數大寫
%e 浮點數格式1
%E 浮點數格式2
%f 浮點數格式3
%g 浮點數格式4
%G 浮點數格式5
%% 文字%
用法:
示例:
>>>args = ["hello","world","!","I'm","Python」] >>>name = 'monkey' >>>age = 18 >>>gender = '男' >>>」name :{} age :{} ".format(name,age) # 位置傳參 >>>name :monkey age :20 >>>'{0[0]} {0[1]} {0[2]} {0[3]} {0[4]}'.format(args) # 下標傳參 >>>hello world ! I'm Python >>>"姓名:{name} 年齡 {age} 性別 {gender}".format(name = name,age = age,gender = gender) # 關鍵字傳參 >>>姓名:monkey 年齡 18 性別 男
format格式說明:
{}中的格式限定符
string = 'illoveTianTAnMen{}' >>>string.capitalize()) # 首字母大寫 Illovetiantanmen{} >>>string.count('ia') # 統計string中 「ia」的個數 1 >>>string.center(30,'*') # 定長的輸出30字符 string 居中 不夠的兩邊補 ‘*’ '******illoveTianTAnMen{}******' >>>string.encode(encoding='utf-8',errors='strict') # 對string按’utf-8’編碼成bytes類型 b'illoveTianTAnMen{}' >>>string.isalnum() # 判斷string是不是純數字和大小寫字母的組合 False >>>string.isalpha() # 判斷string是不是純英文 False >>>string.isdidigit() # 判斷string是不是純數字 False >>>string.isupper() # 判斷是否所有是大寫 False >>>'Monkey\n'.strip() # 去掉所有的空格或回車 'Monkey' >>>'Monkeyli'.replace('l','L',1)) # 將第一個字符換成第二個字符第三參數爲替換幾個默認爲所有替換 'MonkeyLi' >>>'1+2+3+4'.split('+') # 將字符串按照’元素‘分割成一個列表 ['1','2','3','4'] >>>'MonkeyLi'.swapcase() # 交換空間,將大寫轉化成小寫小寫轉大寫 'mONKEYlI' >>>'JIAJIA’.zfill(50) # 不夠的位數填零 000000000000000000000000000000000000000000000JIAJIA
list.__doc__():
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.
列表是一個容器類型的可變類型,其中存放的是對象的引用而不是對象自己。當經過索引給列表賦值時只是講對象的引用放入列表中對應的位置。
>>> name = 'monkey' >>> l = [name] >>> l[0] = 'Mike' >>> l ['Mike'] >>> l[0] 'Mike'
列表的索引和切片同String類型如出一轍,在Python中 全部的索引和切片操做只要是被支持的,那麼都和字符串如出一轍。
#!/usr/bin/env python3 #_*_ coding: utf-8 _*_ __author__ = "monkey" test_list1 = list(range(0,10,2)) test_list2 = list(range(1,10,2)) # 列表的增長 test_list2.append(7) # From documents" Append object to the end of the list." test_list2.insert(111,'inser_value') # 若是 輸入的 index 值超過了列表自己 index的最大值 就把value 添加到最後 # 若是 輸入的 index 值超過了列表自己 index的最小值 就把value 添加到最前面 test_list1.extend(test_list2) # From documents " Extend list by appending elements from the iterable. " # 列表的刪除 test_list1.remove(1) # From documents "Remove first occurrence of value." # 刪除 給定的元素 # 若是刪除的元素不存在列表中 將會報 ValueError # 若是刪除的元素在列表裏由多個值,將會刪除第一個匹配到的值 # ValueError: list.remove(x): x not in list tmp = test_list1.pop(2) # pop()方法將會返回被刪除元素的 值 (接受一個index 刪除這個元素,並返回這個元素!) # pop()方法 接受一個 index值 若是這個index不存在,將會拋出IndexError # 刪除index指向的值 缺省爲 -1 即默認的刪除最後一個元素 # From documents:Raises IndexError if list is empty or index is out of range. test_list1.clear() # From documents " Remove all items from list. " # clear 方法將會完全的清空列表,不會刪除這個列表 區別於del方法 清除掉的是對象的數據 而不是對象的引用 # del test_list1 # 將會完全的刪除list 變量名的引用 不一樣於C的free 和 C++的delete 不會釋放掉內存, # 而是解除了變量名"test_list1"對 list(range(0,10,2))對象的引用 並非刪除了對象 # list(range(0,10,2)) 對象仍然存在!例如 a = 1 c = a del a print(c) 仍然能 # 輸出1 可是print(a)會報錯:NameError: name 'a' is not defined # 這是引用被刪除,而不是引用的對象自己被刪除 # del test_list1[1] # del 不是list的專有的方法,可是能實現list的刪除操做! # 此時del刪除的是 # 列表的修改 test_list2[2] = 'new_value' #其餘操做 test = test_list2.count(7)test = test_list2.index(7)# From documents " Return number of occurrences of value. " # -*-排序 test = [1,234,45,2,66,92] test.sort()# sort 方法按照ASCII碼順序進行排序:特殊字符>數字>大寫>小寫> # sort 方法 要求列表中的元素類型必須一致 # sort 方法的排序是列表自己 無返回值 # -*-反轉 test.reverse() # reverse 方法是在原內存上修改的,而不是建立一個新的對象,即無返回值
三元運算
a = 2 b = 4 >>>max = a if a>b else b # 經典三元表達式a b 比大小 >>>max 4 c = 6 >>>max = (a if a>b else b) if (a if a>b else b)>c else c # a b c 三個數比大小 >>>max 6 # 三元表達式用來 過濾數據 保護程序的穩定性 # 返回參數中全部數字或看起來像數字的和 def func(*args): return sum(int(tmp) if type(tmp) is int or tmp.isdigit() and int(tmp) else 0 for tmp in args) >>>func(1,'w3e','1',2,3,'24sdfsd','sfdsfsd')) 7
列表生成式
>>>num_list = [random.randint(1,20) for i in range(10)] # 生成一個包含10個隨機數的列表 >>>num_list [10, 8, 1, 7, 17, 16, 19, 7, 2, 13] >>>["Element:{}".format(i) for i in num_list] # 生成20個「Elemen?」的列表 ['Element:10', 'Element:8', 'Element:1', 'Element:7', 'Element:17', 'Element:16', 'Element:19', 'Element:7', 'Element:2', 'Element:13'] >>>["AU{}".format(i) for i in num_list if i%2==0] # 帶過濾器的生成式 ['AU10', 'AU8', 'AU16', 'AU2'] def deal(x): if x>10 and x%2==0: return True >>>["func{}".format(i) for i in num_list if deal(i)] # 帶邏輯函數的生成式 ['func16']
tuple.__doc__:
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items
If the argument is a tuple, the return value is the same object.
# 單純的一個括號 就是一個 空的元組對象 >>>type(()) test_tuple = ('name',1,'age',2,1) # 元組 除魔術方法外 只有兩個方法 index 和 counts # index # 對象不存在就會報錯 >>>test_tuple.index(2,3) 3 # index方法最多能夠接受三個參數 第一個爲對象 第二個爲 開始的索引值 第三個爲 結束的索引值 >>>test_tuple.count(1) # 對象不存在 返回0 2 #tuple.__add__() >>>new_tuple = 1,1,1,1 >>>new_tuple_add = new_tuple.__add__(test_tuple) >>>new_tuple_add (1, 1, 1, 1, 'name', 1, 'age', 2, 1) >>>lst= [1,2,3] >>>mytuple=(1,2,lst) >>>mytuple[2][0] = 'new_element’ >>>mytuple (1, 2, ['new_element', 2, 3]) # 元組也是一個容器對象,當元組中的元素是一個可變對象的引用時,能夠經過元組來更改這個可變對象。 # 元組的概念很簡單,可能是用來承接多個對象時候使用 # Python的返回值支持多返回,多賦值,就是藉助於 元組 實現的 test = a,b,c = 1,2,3 print(test) print('(a,b,c):',id((a,b,c))) print('test:',id(test)) print('a:',id(a)) print('b:',id(b)) print('c:',id(c)) print('1:',id(1)) print('2:',id(2)) print('3:',id(3)) # 觀察 內存地址 # test = a,b,c = 1,2,3 # 將 a,b,c 組成元組 並被 test引用,然後,a,b,c 分別成爲對象1 ,2 ,3 的引用
set.__doc__:
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
集合(set)是一個無序的不重複元素序列,所以它不支持索引和切片操做。
可使用大括號 { } 或者 set() 函數建立集合。
集合多用來作去重操做
注意:建立一個空集合必須用 set() 而不是 { },由於 { } 是用來建立一個空字典。
>>> lst = ['new_element', 2, 3] >>> myset = set() >>> myset.add('Python') # 若是元素已存在,則不進行任何操做。添加一個元素 >>> myset {'Python'} >>> myset.update(lst) # 參數能夠是列表,元組,字典等 能夠用一次添加多個元素(先被打散,而後添加)當字典被傳入時,默認的只添加字典的鍵!而不會添加值 >>> myset {3, 'new_element', 'Python', 2} >>> myset.update({'name':18}) # 同時 能夠接受多個參數 用 逗號 分割 >>> myset {3, 'new_element','name’, 'Python', 2} >>> myset.remove('name') # 元素存在就刪除 不存在就 報錯 錯誤類型 「KeyError」 >>> myset {'new_element', 2, 3, 'Python'} >>> myset.discard('test') # 刪除元素,不存在 不報錯 >>> myset {'new_element', 2, 3, 'Python'} >>> myset.pop() # 隨機的刪除一個元素 而且將這個元素返回 (交互模式下 老是刪除第一個元素) 'new_element' >>> myset {2, 3, 'Python'} >>> myset.clear() # 清空集合 >>>myset set()
當建立集合時 :
myset = set(('Python')) ---> 建立的是 {'Python'}
myset = set('Python') ---> 建立的是 {'o','n','t','y','P','h'} 而不是 指望的 {'Python'}
添加元素時:
set() s.update( {"C++"} ) 將字符串添加到集合中,有重複的會忽略
set() s.update("C++") 會將"C++"打散加入集合 獲得的將不是指望的 將 "C++" 添加進集合
關於pop操做 當集合爲list轉化而來 每次pop都是首元素 (這樣的觀點是不正確的)
下面是一個驗證代碼
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ __author__ = "monkey" import random def test_func(): lst = [random.randint(1, 20) for i in range(20)] myset = set(lst) if lst[0] == myset.pop(): return True return False flag = True while test_func(): pass print("循環結束,pop()方法是隨機的!")