Python字符串、列表、元組、字典、集合的補充實例詳解
本文實例講述了Python字符串、列表、元組、字典、集合。分享給大家供大家參考,具體如下:
附加:
python的很多編譯器提供了代碼補全功能,并且在填入?yún)?shù)時提供提示功能


字符串
1.常用函數(shù):
字符串是不可變對象,字符串的方法都不會改變原字符串的數(shù)據(jù)
s=" hEllo world!\t "
print("s.capitalize():",s.capitalize())#標(biāo)題格式化
print("s.center(20,'-'):",s.center(20,'-'))#將字符串居中填充,填充元素為指定字符,總字符數(shù)為指定數(shù)量
print("s.count('l'):",s.count('l'))#統(tǒng)計某字符串出現(xiàn)次數(shù)
print("s.endswith:",s.endswith('d!'))#判斷字符串是否以d!結(jié)尾
print("s.find('o'):",s.find('o'))#查找指定元素,找到返回其索引
print("s.index('o'):",s.index('o'))#查找指定元素,找到返回其索引
sep='ABC'
print("s.join(sep):",s.join(sep))#將原字符s插入到目標(biāo)的每一個字符(或元素對象)中間
print("s.lower():",s.lower())#全轉(zhuǎn)成小寫
print("s.replace('l','j',1):",s.replace('l','j',1))#替換指定字符,最后一個是替換數(shù)量
print("s.split():",s.split())#切割字符串,切割字符為指定字符
print("s.strip():",s.strip())#去除左右空格元素,rstrip是只去除右邊,lstrip是只去除右邊
print("s.upper():",s.upper())#全轉(zhuǎn)大寫
"""is系列:
isdigit()-》是否是數(shù)字,isalnum()-》是否為字母或數(shù)字,isalpha()-》是否為英文字母
islower()-》是否全小寫,
"""
上訴代碼結(jié)果:
s.capitalize(): hello world!
s.center(20,'-'): -- hEllo world! ---
s.count('l'): 3
s.endswith: False
s.find('o'): 5
s.index('o'): 5
s.join(sep): A hEllo world! B hEllo world! C
s.lower(): hello world!
s.replace('l','j',1): hEjlo world!
s.split(): ['hEllo', 'world!']
s.strip(): hEllo world!
s.upper(): HELLO WORLD!
2.字符串格式化:
python 字符串格式化--這個好像參數(shù)給的好全
>>> s="%d is 250"
>>> s%250
'250 is 250'
>>> b = "%(name)+10s————————%(age)-10d————————"%{'name':'xx','age':20}
>>> print(b)
xx————————20 ————————
>>> s="{:d} is a 250"
>>> s.format(250)
'250 is a 250'
>>> a1 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{:c}".format(15, 15, 15, 15, 15, 15.87623,65)
>>> print(a1)
numbers: 1111,17,15,f,F, 1587.623000%,A
>>> s="{} {} 250"
>>> s.format(250,"500-250")
'250 500-250 250'
>>> s.format(250,"500-250")
'250 500-250 250'
3.原始字符串:
起因:為了避免過多使用\來轉(zhuǎn)義,當(dāng)字符串格式為 r"字符串" 時 里面的字符全部當(dāng)成字符,如\n不再當(dāng)初換行
>>> print("a\tb")
a b
>>> print(r"a\tb")
a\tb
但字符串無法處理,如果結(jié)尾是一個 \ :
>>> print(r"c:\a\b") c:\a\b >>> print(r"c:\a\b\") SyntaxError: EOL while scanning string literal >>> print(r"c:\a\b\\") c:\a\b\\ >>> print(r"c:\a\b"+"\\") c:\a\b\
這樣的情況最好使用字符串拼接來處理。
列表
1.常用函數(shù):
print("查".center(20,'-'))
list_find=['apple','banana','pen',1,2,3]
#查找指定元素的下標(biāo)
print(list_find.index('apple'))
#查找某元素存在的數(shù)量
print(list_find.count("apple"))
print("增".center(20,'-'))
list_add=['apple','banana']
#追加元素到末尾
list_add.append("哈密瓜")
print(list_add)
#插入元素到指定位置
list_add.insert(0,"蘋果")
print(list_add)
print("刪".center(20,'-'))
list_del=[1,2,3,4,"apple",5,6,7,8]
#從列表中取出元素(刪除式取出),pop可以填參數(shù),參數(shù)為刪除元素的下標(biāo)
list_del.pop()
print(list_del)
#remove刪除指定元素名的元素
list_del.remove("apple")
print(list_del)
#刪除對應(yīng)元素空間
del list_del[0]
print(list_del)
print("其他".center(20,'-'))
list_test4=['a','b','d','c']
list_test5=[1,2,3,4]
#擴展列表
list_test5.extend(list_test4)
print(list_test5)
#對列表進行排序
list_test4.sort()
print(list_test4)#注:py3無法對元素類型不同的進行排序
#反轉(zhuǎn)列表
list_test5.reverse()
print(list_test5)
上述代碼運行結(jié)果:
---------查----------
0
1
---------增----------
['apple', 'banana', '哈密瓜']
['蘋果', 'apple', 'banana', '哈密瓜']
---------刪----------
[1, 2, 3, 4, 'apple', 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7]
---------其他---------
[1, 2, 3, 4, 'a', 'b', 'd', 'c']
['a', 'b', 'c', 'd']
['c', 'd', 'b', 'a', 4, 3, 2, 1]
2.列表生成式:
# 過程:1.迭代 迭代器 中的每個元素;
# 2.每次迭代都先把結(jié)果賦值給變量,然后通過代入表達式得到一個新的計算值;
#3. 最后把所有表達式得到的計算值以一個新列表的形式返回。
print("普通的列表生成式".center(50,'-'))
#[表達式 for 變量 in 迭代器]
list1=[i for i in range(10)]
print(list1)
list2=[i*i for i in range(10,20)]
print(list2)
print("\n")
print("帶判斷的列表生成式".center(50,'-'))
#[表達式 for 變量 in 迭代器 if 表達式]
list3=[i for i in range(10) if i%2==0]
print(list3)
print("\n")
print("嵌套循環(huán)的列表生成式".center(50,'-'))
#[表達式 for 變量 in 迭代器 for 變量 in 迭代器]
list4=[x*y for x in range(5) for y in range(5)]
print(list4)
print("\n")
上述代碼運行結(jié)果:
---------------------普通的列表生成式---------------------
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
--------------------帶判斷的列表生成式---------------------
[0, 2, 4, 6, 8]
--------------------嵌套循環(huán)的列表生成式--------------------
[0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 2, 4, 6, 8, 0, 3, 6, 9, 12, 0, 4, 8, 12, 16]
字典
1.常用函數(shù):
d1={1:"蘋果","雪碧":"雪梨"}
d1.clear()#清空字典
print(d1)
d1={1:"蘋果","雪碧":"雪梨"}
print(d1.get(1))#獲取字典的指定鍵的結(jié)果
print(d1.get(3))#如果獲取不存在的鍵,返回None
print(d1.items())#獲取字典的所有鍵值對
print(d1.keys())#獲取字典的鍵
print(d1.values())#獲取字典的值
print(d1.pop(1))#取出指定下標(biāo)結(jié)果
print(d1.popitem())#不需索引的彈出結(jié)果
print(d1)
d1={1:"蘋果","雪碧":"雪梨"}
d1.update({1:'apple',3:'pen'})#更新結(jié)果,同鍵名更新,新鍵名則添加結(jié)果
print(d1)
上述代碼運行結(jié)果:
{}
蘋果
None
dict_items([(1, '蘋果'), ('雪碧', '雪梨')])
dict_keys([1, '雪碧'])
dict_values(['蘋果', '雪梨'])
蘋果
('雪碧', '雪梨')
{}
{1: 'apple', '雪碧': '雪梨', 3: 'pen'}
集合
1.常用函數(shù):
s1=set(['a','b','c'])
print(s1.pop())#隨機刪除集合中的某個元素,取到元素后返回元素的值
print(s1)
s3={'a','d'}
s1.update(s3)#更新
print(s1)
s1.add('f')#增加元素
print(s1)
s1.clear()#清空
s1=set(['a','b','c','f'])
print(s1)
s1.remove('a')#刪除目標(biāo)元素,但集合中如無元素,會報錯
print(s1)
s1.discard('g')#如果集合中無元素,不報錯;有元素,就刪除
print(s1)
b={'a','b','g'}
print("s1.difference(b)")
print(s1.difference(b))# 取集合s中有,b中沒有的元素,并返回由此元素組成的集合
print("s1.interscetion(b)")
print(s1.intersection(b))#交集,兩s和b中的交集,返回s,b中都存在的元素組成的集合
print("s1.issubset(b)")
print(s1.issubset(b))#判斷s是否是b的子集
print("s1.issuperset(b)")
print(s1.issuperset(b)) #判斷s是否是b的父集
print("s1.symmetric_difference(b)")
print(s1.symmetric_difference(b)) #取差集,并創(chuàng)建一個新的集合
print("s1.union(b)")
print(s1.union(b)) #并集
print("symmetric_difference_update")
print(s1)
s1.symmetric_difference_update(b)#無返回值
print(s1)
"""
xxxx_update的會覆蓋s1的值,如:
s1.symmetric_difference_update()
得出symmetric_difference的結(jié)果后會覆蓋s1的值
"""
上述代碼結(jié)果:
a
{'c', 'b'}
{'c', 'b', 'd', 'a'}
{'c', 'b', 'd', 'f', 'a'}
{'a', 'c', 'b', 'f'}
{'c', 'b', 'f'}
{'c', 'b', 'f'}
s1.difference(b)
{'c', 'f'}
s1.interscetion(b)
{'b'}
s1.issubset(b)
False
s1.issuperset(b)
False
s1.symmetric_difference(b)
{'a', 'g', 'c', 'f'}
s1.union(b)
{'g', 'c', 'b', 'f', 'a'}
symmetric_difference_update
{'c', 'b', 'f'}
None
{'g', 'c', 'f', 'a'}
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python列表(list)操作技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
- python字符串,元組,列表,字典互轉(zhuǎn)代碼實例詳解
- python判斷變量是否為int、字符串、列表、元組、字典的方法詳解
- 在Python中字符串、列表、元組、字典之間的相互轉(zhuǎn)換
- python中for循環(huán)把字符串或者字典添加到列表的方法
- Python基礎(chǔ)學(xué)習(xí)之基本數(shù)據(jù)結(jié)構(gòu)詳解【數(shù)字、字符串、列表、元組、集合、字典】
- Python3中的列表,元組,字典,字符串相關(guān)知識小結(jié)
- 淺談python中列表、字符串、字典的常用操作
- Python字符串、元組、列表、字典互相轉(zhuǎn)換的方法
- Python列表(list)、字典(dict)、字符串(string)基本操作小結(jié)
- Python?編程操作連載之字符串,列表,字典和集合處理
相關(guān)文章
Python數(shù)據(jù)分析之?Matplotlib?散點圖繪制
這篇文章主要介紹了Python數(shù)據(jù)分析之?Matplotlib?散點圖繪制,散點圖又稱散點圖,是使用多個坐標(biāo)點的分布反映數(shù)據(jù)點分布規(guī)律、數(shù)據(jù)關(guān)聯(lián)關(guān)系的圖表,下文對散點圖的詳細(xì)介紹及繪制,需要的小伙伴可以參考以一下2022-05-05
Python for循環(huán)及基礎(chǔ)用法詳解
這篇文章為大家介紹python for 循環(huán),它常用于遍歷字符串、列表、元組、字典、集合等序列類型,逐個獲取序列中的各個元素2019-11-11
Python ORM框架SQLAlchemy學(xué)習(xí)筆記之?dāng)?shù)據(jù)添加和事務(wù)回滾介紹
這篇文章主要介紹了Python ORM框架SQLAlchemy學(xué)習(xí)筆記之?dāng)?shù)據(jù)添加和事務(wù)回滾介紹,需要的朋友可以參考下2014-06-06
Python實現(xiàn)圖像去噪方式(中值去噪和均值去噪)
今天小編就為大家分享一篇Python實現(xiàn)圖像去噪方式(中值去噪和均值去噪),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
matplotlib 多個圖像共用一個colorbar的實現(xiàn)示例
這篇文章主要介紹了matplotlib 多個圖像共用一個colorbar的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
python pow函數(shù)的底層實現(xiàn)原理介紹
這篇文章主要介紹了python pow函數(shù)的底層實現(xiàn)原理介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Python實現(xiàn)爬取網(wǎng)頁中動態(tài)加載的數(shù)據(jù)
這篇文章主要介紹了Python實現(xiàn)爬取網(wǎng)頁中動態(tài)加載的數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
python中dict獲取關(guān)鍵字與值的實現(xiàn)
這篇文章主要介紹了python中dict獲取關(guān)鍵字與值的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

