Python列表 字串 字典等常用操作

2021-08-10 11:52:11 字數 2528 閱讀 1562

【字典】:

len(字典):獲取字典的鍵值對數量

字典.keys() 所有key列表

字典.values() 所有value列表

字典.items()所有(key,value)元組列表

字典.pop(key) 刪除指定鍵值對,key不存在會報錯

字典.popitem() 隨機刪除乙個鍵值對

字典.clear()清空字典

字典.[key] 從字典中取對應key的值,key不存在會報錯

字典.get(key) 從字典中取對應key的值,key不存在不會報錯

【字串】:

1.判斷型別 - 9

string.isspace() 如果 string 中只包含空格,則返回 true

string.isalnum() 如果 string 至少有乙個字元並且所有字元都是字母或數字則返回 true

string.isalpha() 如果 string 至少有乙個字元並且所有字元都是字母則返回 true

string.isdecimal() 如果 string 只包含數字則返回 true,全形數字

string.isdigit() 如果 string 只包含數字則返回 true,全形數字、⑴、\u00b2

string.isnumeric() 如果 string 只包含數字則返回 true,全形數字,漢字數字

string.istitle() 如果 string 是標題化的(每個單詞的首字母大寫)則返回 true

string.islower() 如果 string 中包含至少乙個區分大小寫的字元,並且所有這些(區分大小寫的)字元都是小寫,則返回 true

string.isupper() 如果 string 中包含至少乙個區分大小寫的字元,並且所有這些(區分大小寫的)字元都是大寫,則返回 true

2.查詢和替換 - 7

string.startswith(str) 檢查字串是否是以 str 開頭,是則返回 true

string.endswith(str) 檢查字串是否是以 str 結束,是則返回 true

string.find(str, start=0, end=len(string)) 檢測 str 是否包含在 string 中,如果 start 和 end 指定範圍,則檢查是否包含在指定範圍內,如果是返回開始的索引值,否則返回 -1

string.rfind(str, start=0, end=len(string)) 類似於 find(),不過是從右邊開始查詢

string.index(str, start=0, end=len(string)) 跟 find() 方法類似,不過如果 str 不在 string 會報錯

string.rindex(str, start=0, end=len(string)) 類似於 index(),不過是從右邊開始

string.replace(old_str, new_str, num=string.count(old)) 把 string 中的 old_str 替換成 new_str,如果 num 指定,則替換不超過 num 次

3.大小寫轉換 - 5

string.capitalize() 把字串的第乙個字元大寫

string.title() 把字串的每個單詞首字母大寫

string.lower() 轉換 string 中所有大寫字元為小寫

string.upper() 轉換 string 中的小寫字母為大寫

string.swapcase() 翻轉 string 中的大小寫

4.文字對齊 - 3

string.ljust(width) 返回乙個原字串左對齊,並使用空格填充至長度 width 的新字串

string.rjust(width) 返回乙個原字串右對齊,並使用空格填充至長度 width 的新字串

string.center(width) 返回乙個原字串居中,並使用空格填充至長度 width 的新字串

5.去除空白字元 - 3

string.lstrip() 截掉 string 左邊(開始)的空白字元

string.rstrip() 截掉 string 右邊(末尾)的空白字元

string.strip() 截掉 string 左右兩邊的空白字元

6.拆分和連線 - 5

string.partition(str) 把字串 string 分成乙個 3 元素的元組 (str前面, str, str後面)

string.rpartition(str) 類似於 partition() 方法,不過是從右邊開始查詢

string.split(str=」「, num) 以 str 為分隔符拆分 string,如果 num 有指定值,則僅分隔 num + 1 個子字串,str 預設包含 『\r』, 『\t』, 『\n』 和空格

string.splitlines() 按照行(『\r』, 『\n』, 『\r\n』)分隔,返回乙個包含各行作為元素的列表

string.join(seq) 以 string 作為分隔符,將 seq 中所有的元素(的字串表示)合併為乙個新的字串

python字串 元組 列表 字典互轉

coding utf 8 1 字典 dict 字典轉為字串,返回 print type str dict str dict 字典可以轉為元組,返回 age name class print tuple dict 字典可以轉為元組,返回 7,zara first print tuple dict.va...

python字串 元組 列表 字典互轉

coding utf 8 1 字典 dict 字典轉為字串,返回 print type str dict str dict 字典可以轉為元組,返回 age name class print tuple dict 字典可以轉為元組,返回 7,zara first print tuple dict.va...

python字串 元組 列表 字典互轉

coding utf 8 1 字典 dict 字典轉為字串,返回 print type str dict str dict 字典可以轉為元組,返回 age name class print tuple dict 字典可以轉為元組,返回 7,zara first print tuple dict.va...