Python 中有四個很是經常使用的數據類型,分別是字符串,列表,元組和字典。下面就來介紹這四個基本的數據類型。python
Python 對字符串的處理是很是強的,因此掌握一些 Python 對字符串的基本操做是很是有必要的.linux
賦值git
str = 'hello'
填字符串windows
str = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
轉換數組
pi = 3.14 print 'pi = ' + str(pi)
大小寫轉換微信
str.lower() str.upper()
去除首尾空格數據結構
str.strip()
判斷字符裏全部的字符是否是字母/數字/空格app
str.isalpha() str.isdigit() str.isspace()
判斷字符串是否是以某個子串開頭/結尾函數
str.startswith(' ') str.endswith()
查找子串在字符串中的位置,沒找到返回-1ui
str.find('th')
字符串的替換
str.replace('old','new')
字符串的分割,返回 list
str.split('delim') 'delim'.join(list)
在 Python2 裏面默認都是用 unicode 編碼的,而 windows 裏面的文件默認是 gbk 編碼,而 linux 裏面的文件默認的是 utf8 編碼,因此編碼之間的轉換是必不可少的.
定義unicode字符串
ustr = u'A unicode \u018e string \xf1'
轉換utf-8編碼
utfstr = ustr.encode('utf-8')
轉換會unicode編碼
unistr = unicode(utfstr, 'utf-8')
列表是 Python 裏面一個很重要的數據結構,也是很是經常使用的一個數據結構.
初始化
colors = ['red', 'blue', 'green']
擴展
# 選擇鏈表fruits中包含字符'a',並所有轉換成大寫 fruits = ['apple', 'cherry', 'bannana', 'lemon'] # ['APPLE', 'BANNANA'] afruits = [ s.upper() for s in fruits if 'a' in s ]
添加元素
list.append(elem)
在i位置添加元素 elem
list.insert(i,elem)
將 list2 中的元素添加到 list 中
list.extend(list2)
獲取元素 elem 的索引號
list.index(elem)
刪除第一個出現的元素 elem
list.remove(elem)
刪除第 i 個元素
list.pop(i)
給 list 排序
list.sort()
顛倒 list
list.reverse()
sorted 基本方法
a = [5, 1, 4, 3] print sorted(a) ## [1, 3, 4, 5] print sorted(a, reverse=True) ##[5, 4, 3, 1] print a ## [5, 1, 4, 3]
sorted 按關鍵字排序
以字符串的長度排序
strs = ['ccc', 'aaaa', 'd', 'bb'] print sorted(strs, key=len) ## ['d', 'bb', 'ccc', 'aaaa'] #len表明len()這個函數
其函數處理細節見下圖:
以自定義關鍵字函數排序
# 根據字符串最後一個字符來排序 strs = ['xc', 'zb', 'yd' ,'wa'] # 定義一個函數,輸入是一個字符串,返回最後一個字符 def MyFn(s): return s[-1] # 傳遞key=MyFn做爲參數 print sorted(strs, key=MyFn) ## ['wa', 'zb', 'xc', 'yd']
元組就至關於數組.其元素的大小沒法改變.
賦值(用圓圓括號包含元素)
tuple = (1, 2, 'hi') print len(tuple) ## 3 print tuple[2] ## hi
更改元素
# 報錯,元組元素沒法更改 tuple[2] = 'bye' # this works tuple = (1, 2, 'bye')
賦值
# 能夠以{}開始構建空字典,而後以賦值的形式給字典添加鍵值對 dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
查看和更改元素
print dict['a'] # 查看'a'對應的值 'alpha' dict['a'] = 6 # 給'a'從新賦值 if 'z' in dict: print dict['z'] # 避免報錯 print dict.get('z') # None (instead of KeyError)
獲取字典關鍵字
dict.keys()
獲取字典值
dict.values()
獲取字典鍵值對(返回的是一個元組鏈表)
dict.items()
循環中獲取鍵和值
for k,v in dict.items(): print k, '>', v
刪除元素(對 list 也適用)
dict = {'a':1, 'b':2, 'c':3} del dict['b'] # 刪除'b'元素 print dict ## {'a':1, 'c':3}
sorted 方法
dict1={'A': 9, 'C': 5, 'B': 1, 'E': 14, 'D': 3, 'G': 3, 'F': 3, 'I': 9, 'H': 7, 'J': 1, 'L': 2, 'O': 8, 'N': 3, 'P': 4, 'S': 10, 'R': 5, 'U': 1, 'T': 17, 'W': 1, 'V': 1} #對字典按值排序,以元組的形式返回 print sorted(dict1.iteritems(),key=lambda dict1:dict1[1],reverse=True) #對字典按鍵排序,以元組的形式返回 print sorted(dict1.iteritems(),key=lambda dict1:dict1[0],reverse=False)
若是該文章對您產生了幫助,或者您對技術文章感興趣,能夠關注微信公衆號: 技術茶話會, 可以第一時間收到相關的技術文章,謝謝!