1. 程式人生 > 程式設計 >Python字串、列表、元組、字典、集合的補充例項詳解

Python字串、列表、元組、字典、集合的補充例項詳解

本文例項講述了Python字串、列表、元組、字典、集合。分享給大家供大家參考,具體如下:

附加:

python的很多編譯器提供了程式碼補全功能,並且在填入引數時提供提示功能

字串

1.常用函式:

字串是不可變物件,字串的方法都不會改變原字串的資料

s=" hEllo world!\t "
print("s.capitalize():",s.capitalize())#標題格式化
print("s.center(20,'-'):",s.center(20,'-'))#將字串居中填充,填充元素為指定字元,總字元數為指定數量
print("s.count('l'):",s.count('l'))#統計某字串出現次數
print("s.endswith:",s.endswith('d!'))#判斷字串是否以d!結尾
print("s.find('o'):",s.find('o'))#查詢指定元素,找到返回其索引
print("s.index('o'):",s.index('o'))#查詢指定元素,找到返回其索引
sep='ABC'
print("s.join(sep):",s.join(sep))#將原字元s插入到目標的每一個字元(或元素物件)中間
print("s.lower():",s.lower())#全轉成小寫
print("s.replace('l','j',1):",s.replace('l',1))#替換指定字元,最後一個是替換數量
print("s.split():",s.split())#切割字串,切割字元為指定字元
print("s.strip():",s.strip())#去除左右空格元素,rstrip是隻去除右邊,lstrip是隻去除右邊
print("s.upper():",s.upper())#全轉大寫
"""is系列:
isdigit()-》是否是數字,isalnum()-》是否為字母或數字,isalpha()-》是否為英文字母
islower()-》是否全小寫,
"""

上訴程式碼結果:

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',1): hEjlo world!
s.split(): ['hEllo','world!']
s.strip(): hEllo world!
s.upper(): HELLO WORLD!

2.字串格式化:

python 字串格式化--這個好像引數給的好全

>>> 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.87623,65)
>>> print(a1)
numbers: 1111,17,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.原始字串:

起因:為了避免過多使用\來轉義,當字串格式為 r"字串" 時 裡面的字元全部當成字元,如\n不再當初換行

>>> print("a\tb")
a  b
>>> print(r"a\tb")
a\tb

但字串無法處理,如果結尾是一個 \ :

>>> 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.常用函式:

print("查".center(20,'-'))
list_find=['apple','banana','pen',1,2,3]
#查詢指定元素的下標
print(list_find.index('apple'))
#查詢某元素存在的數量
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,3,4,"apple",5,6,7,8]
#從列表中取出元素(刪除式取出),pop可以填引數,引數為刪除元素的下標
list_del.pop()
print(list_del)
#remove刪除指定元素名的元素
list_del.remove("apple")
print(list_del)
#刪除對應元素空間
del list_del[0]
print(list_del)
print("其他".center(20,'-'))
list_test4=['a','b','d','c']
list_test5=[1,4]
#擴充套件列表
list_test5.extend(list_test4)
print(list_test5)
#對列表進行排序
list_test4.sort()
print(list_test4)#注:py3無法對元素型別不同的進行排序
#反轉列表
list_test5.reverse()
print(list_test5)

上述程式碼執行結果:

---------查----------
0
1
---------增----------
['apple','哈密瓜']
['蘋果','apple','哈密瓜']
---------刪----------
[1,7]
[1,7]
[2,7]
---------其他---------
[1,'a','c']
['a','c','d']
['c',1]

2.列表生成式:

# 過程:1.迭代 迭代器 中的每個元素;
# 2.每次迭代都先把結果賦值給變數,然後通過代入表示式得到一個新的計算值;
#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("巢狀迴圈的列表生成式".center(50,'-'))
#[表示式 for 變數 in 迭代器 for 變數 in 迭代器]
list4=[x*y for x in range(5) for y in range(5)]
print(list4)
print("\n")

上述程式碼執行結果:

---------------------普通的列表生成式---------------------
[0,8,9]
[100,121,144,169,196,225,256,289,324,361]


--------------------帶判斷的列表生成式---------------------
[0,8]


--------------------巢狀迴圈的列表生成式--------------------
[0,9,12,16]

字典

1.常用函式:

d1={1:"蘋果","雪碧":"雪梨"}
d1.clear()#清空字典
print(d1)
d1={1:"蘋果","雪碧":"雪梨"}
print(d1.get(1))#獲取字典的指定鍵的結果
print(d1.get(3))#如果獲取不存在的鍵,返回None
print(d1.items())#獲取字典的所有鍵值對
print(d1.keys())#獲取字典的鍵
print(d1.values())#獲取字典的值
print(d1.pop(1))#取出指定下標結果
print(d1.popitem())#不需索引的彈出結果
print(d1)
d1={1:"蘋果","雪碧":"雪梨"}
d1.update({1:'apple',3:'pen'})#更新結果,同鍵名更新,新鍵名則新增結果
print(d1)

上述程式碼執行結果:

{}
蘋果
None
dict_items([(1,'蘋果'),('雪碧','雪梨')])
dict_keys([1,'雪碧'])
dict_values(['蘋果','雪梨'])
蘋果
('雪碧','雪梨')
{}
{1: 'apple','雪碧': '雪梨',3: 'pen'}

集合

1.常用函式:

s1=set(['a','c'])
print(s1.pop())#隨機刪除集合中的某個元素,取到元素後返回元素的值
print(s1)
s3={'a','d'}
s1.update(s3)#更新
print(s1)
s1.add('f')#增加元素
print(s1)
s1.clear()#清空
s1=set(['a','f'])
print(s1)
s1.remove('a')#刪除目標元素,但集合中如無元素,會報錯
print(s1)
s1.discard('g')#如果集合中無元素,不報錯;有元素,就刪除
print(s1)
b={'a','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)) #取差集,並建立一個新的集合
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的結果後會覆蓋s1的值
"""

上述程式碼結果:

a
{'c','b'}
{'c','a'}
{'c','f','a'}
{'a','f'}
{'c','f'}
s1.difference(b)
{'c','f'}
s1.interscetion(b)
{'b'}
s1.issubset(b)
False
s1.issuperset(b)
False
s1.symmetric_difference(b)
{'a','g','f'}
s1.union(b)
{'g','a'}
symmetric_difference_update
{'c','f'}
None
{'g','a'}

更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python字串操作技巧彙總》、《Python資料結構與演算法教程》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python函式使用技巧總結》及《Python入門與進階經典教程》

希望本文所述對大家Python程式設計有所幫助。