Python 中有四個非常常用的資料型別,分別是字串,串列,元組和字典,下面就來介紹這四個基本的資料型別,
字串
Python 對字串的處理是非常強的,所以掌握一些 Python 對字串的基本操作是非常有必要的.
字串表示
-
賦值
str = 'hello' -
填字串
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() -
判斷字符里所有的字符是不是字母/數字/空格
str.isalpha() str.isdigit() str.isspace() -
判斷字串是不是以某個子串開頭/結尾
str.startswith(' ') str.endswith() -
查找子串在字串中的位置,沒找到回傳-1
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')
練習題
- 基礎題: string1.py
- 提升題: string2.py
串列
串列是 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 常用方法
-
添加元素
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']
-
練習題
- 基礎題: list1.py
- 提升題: list2.py
元組
元組就相當于陣列.其元素的大小無法改變.
元組表示
-
賦值(用圓圓括號包含元素)
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)
如果該文章對您產生了幫助,或者您對技術文章感興趣,可以關注微信公眾號: 技術茶話會, 能夠第一時間收到相關的技術文章,謝謝!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/253389.html
標籤:Python
上一篇:PHP的可變變數與可變函式
