清單
簡單資料類型
- 整型
<class 'int'>
- 浮點型
<class 'float'>
- 布爾型
<class 'bool'>
容器資料類型
- 清單
<class 'list'>
- 元組
<class 'tuple'>
- 字典
<class 'dict'>
- 集合
<class 'set'>
- 字元串
<class 'str'>
1. 清單的定義
清單是有序集合,沒有固定大小,能夠儲存任意數量任意類型的 Python 對象,文法為
[元素1, 元素2, ..., 元素n]
。
- 關鍵點是「中括号 []」和「逗号 ,」
- 中括号 把所有元素綁在一起
- 逗号 将每個元素一一分開
2. 清單的建立
- 建立一個普通清單
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x, type(x))
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>
x = [2, 3, 4, 5, 6, 7]
print(x, type(x))
# [2, 3, 4, 5, 6, 7] <class 'list'>
- 利用
建立清單range()
【例子】
x = list(range(10))
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
x = list(range(1, 11, 2))
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>
x = list(range(10, 1, -2))
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>
- 利用推導式建立清單
【例子】
x = [0] * 5
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>
x = [0 for i in range(5)]
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>
x = [i for i in range(10)]
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
x = [i for i in range(1, 10, 2)]
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>
x = [i for i in range(10, 1, -2)]
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>
x = [i ** 2 for i in range(1, 10)]
print(x, type(x))
# [1, 4, 9, 16, 25, 36, 49, 64, 81] <class 'list'>
x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x, type(x))
# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99] <class 'list'>
建立一個 4×3的二維數組
【例子】
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]]
print(x, type(x))
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]] <class 'list'>
for i in x:
print(i, type(i))
# [1, 2, 3] <class 'list'>
# [4, 5, 6] <class 'list'>
# [7, 8, 9] <class 'list'>
# [0, 0, 0] <class 'list'>
x = [[0 for col in range(3)] for row in range(4)]
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x = [[0] * 3 for row in range(4)]
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[1][1] = 1
print(x, type(x))
# [[0, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
注意:
由于list的元素可以是任何對象,是以清單中所儲存的是對象的指針。即使儲存一個簡單的
[1,2,3]
,也有3個指針和3個整數對象。
x = [a] * 4
操作中,隻是建立4個指向list的引用,是以一旦
a
改變,
x
中4個
a
也會随之改變。
【例子】
x = [[0] * 3] * 4
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>
a = [0] * 3
x = [a] * 4
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>
- 建立一個混合清單
【例子】
mix = [1, 'lsgo', 3.14, [1, 2, 3]]
print(mix, type(mix))
# [1, 'lsgo', 3.14, [1, 2, 3]] <class 'list'>
- 建立一個空清單
【例子】
empty = []
print(empty, type(empty)) # [] <class 'list'>
清單不像元組,清單内容可更改 (mutable),是以附加 (
append
,
extend
)、插入 (
insert
)、删除 (
remove
,
pop
) 這些操作都可以用在它身上。
3. 向清單中添加元素
-
在清單末尾添加新的對象,隻接受一個參數,參數可以是任何資料類型,被追加的元素在 list 中保持着原結構類型。list.append(obj)
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.append('Thursday')
print(x)
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday']
print(len(x)) # 6
此元素如果是一個 list,那麼這個 list 将作為一個整體進行追加,注意
append()
和
extend()
的差別。
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.append(['Thursday', 'Sunday'])
print(x)
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', ['Thursday', 'Sunday']]
print(len(x)) # 6
-
在清單末尾一次性追加另一個序列中的多個值(用新清單擴充原來的清單)list.extend(seq)
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.extend(['Thursday', 'Sunday'])
print(x)
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday', 'Sunday']
print(len(x)) # 7
嚴格來說
append
是追加,把一個東西整體添加在清單後,而
extend
是擴充,把一個東西裡的所有元素添加在清單後。
-
在編号list.insert(index, obj)
位置插入index
。obj
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.insert(2, 'Sunday')
print(x)
# ['Monday', 'Tuesday', 'Sunday', 'Wednesday', 'Thursday', 'Friday']
print(len(x)) # 6
4. 删除清單中的元素
-
移除清單中某個值的第一個比對項list.remove(obj)
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.remove('Monday')
print(x) # ['Tuesday', 'Wednesday', 'Thursday', 'Friday']
-
移除清單中的一個元素(預設最後一個元素),并且傳回該元素的值list.pop([index=-1])
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
y = x.pop()
print(y) # Friday
y = x.pop(0)
print(y) # Monday
y = x.pop(-2)
print(y) # Wednesday
print(x) # ['Tuesday', 'Thursday']
remove
和
pop
都可以删除元素,前者是指定具體要删除的元素,後者是指定一個索引。
-
删除單個或多個對象。del var1[, var2 ……]
【例子】
如果知道要删除的元素在清單中的位置,可使用
del
語句。
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
del x[0:2]
print(x) # ['Wednesday', 'Thursday', 'Friday']
如果你要從清單中删除一個元素,且不再以任何方式使用它,就使用
del
語句;如果你要在删除元素後還能繼續使用它,就使用方法
pop()
。
5. 擷取清單中的元素
- 通過元素的索引值,從清單擷取單個元素,注意,清單索引值是從0開始的。
- 通過将索引指定為-1,可讓Python傳回最後一個清單元素,索引 -2 傳回倒數第二個清單元素,以此類推。
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', ['Thursday', 'Friday']]
print(x[0], type(x[0])) # Monday <class 'str'>
print(x[-1], type(x[-1])) # ['Thursday', 'Friday'] <class 'list'>
print(x[-2], type(x[-2])) # Wednesday <class 'str'>
切片的通用寫法是
start : stop : step
- 情況 1 - "start :"
- 以
為 1 (預設) 從編号step
往清單尾部切片。start
【例子】
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x[3:]) # ['Thursday', 'Friday']
print(x[-3:]) # ['Wednesday', 'Thursday', 'Friday']
- 情況 2 - ": stop"
- 以
為 1 (預設) 從清單頭部往編号step
切片。stop
【例子】
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[:3]) # ['Monday', 'Tuesday', 'Wednesday']
print(week[:-3]) # ['Monday', 'Tuesday']
- 情況 3 - "start : stop"
- 以
為 1 (預設) 從編号step
往編号start
切片。stop
【例子】
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:3]) # ['Tuesday', 'Wednesday']
print(week[-3:-1]) # ['Wednesday', 'Thursday']
- 情況 4 - "start : stop : step"
- 以具體的
從編号step
往編号start
切片。注意最後把stop
設為 -1,相當于将清單反向排列。step
【例子】
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:4:2]) # ['Tuesday', 'Thursday']
print(week[:4:2]) # ['Monday', 'Wednesday']
print(week[1::2]) # ['Tuesday', 'Thursday']
print(week[::-1])
# ['Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday']
- 情況 5 - " : "
- 複制清單中的所有元素(淺拷貝)。
【例子】
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[:])
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
【例子】淺拷貝與深拷貝
list1 = [123, 456, 789, 213]
list2 = list1
list3 = list1[:]
print(list2) # [123, 456, 789, 213]
print(list3) # [123, 456, 789, 213]
list1.sort()
print(list2) # [123, 213, 456, 789]
print(list3) # [123, 456, 789, 213]
list1 = [[123, 456], [789, 213]]
list2 = list1
list3 = list1[:]
print(list2) # [[123, 456], [789, 213]]
print(list3) # [[123, 456], [789, 213]]
list1[0][0] = 111
print(list2) # [[111, 456], [789, 213]]
print(list3) # [[111, 456], [789, 213]]
6. 清單的常用操作符
- 等号操作符:
==
- 連接配接操作符
+
- 重複操作符
*
- 成員關系操作符
、in
not in
「等号 ==」,隻有成員、成員位置都相同時才傳回True。
清單拼接有兩種方式,用「加号 +」和「乘号 *」,前者首尾拼接,後者複制拼接。
【例子】
list1 = [123, 456]
list2 = [456, 123]
list3 = [123, 456]
print(list1 == list2) # False
print(list1 == list3) # True
list4 = list1 + list2 # extend()
print(list4) # [123, 456, 456, 123]
list5 = list3 * 3
print(list5) # [123, 456, 123, 456, 123, 456]
list3 *= 3
print(list3) # [123, 456, 123, 456, 123, 456]
print(123 in list3) # True
print(456 not in list3) # False
前面三種方法(
append
,
extend
,
insert
)可對清單增加元素,它們沒有傳回值,是直接修改了原資料對象。 而将兩個list相加,需要建立新的 list 對象,進而需要消耗額外的記憶體,特别是當 list 較大時,盡量不要使用 “+” 來添加list。
7. 清單的其它方法
list.count(obj)
統計某個元素在清單中出現的次數
【例子】
list1 = [123, 456] * 3
print(list1) # [123, 456, 123, 456, 123, 456]
num = list1.count(123)
print(num) # 3
list.index(x[, start[, end]])
從清單中找出某個值第一個比對項的索引位置
【例子】
list1 = [123, 456] * 5
print(list1.index(123)) # 0
print(list1.index(123, 1)) # 2
print(list1.index(123, 3, 7)) # 4
list.reverse() 反向清單中元素
【例子】
x = [123, 456, 789]
x.reverse()
print(x) # [789, 456, 123]
list.sort(key=None, reverse=False) 對原清單進行排序。
-
-- 主要是用來進行比較的元素,隻有一個參數,具體的函數的參數就是取自于可疊代對象中,指定可疊代對象中的一個元素來進行排序。key
-
-- 排序規則,reverse
降序,reverse = True
升序(預設)。reverse = False
- 該方法沒有傳回值,但是會對清單的對象進行排序。
【例子】
x = [123, 456, 789, 213]
x.sort()
print(x)
# [123, 213, 456, 789]
x.sort(reverse=True)
print(x)
# [789, 456, 213, 123]
# 擷取清單的第二個元素
def takeSecond(elem):
return elem[1]
x = [(2, 2), (3, 4), (4, 1), (1, 3)]
x.sort(key=takeSecond)
print(x)
# [(4, 1), (2, 2), (1, 3), (3, 4)]
x.sort(key=lambda a: a[0])
print(x)
# [(1, 3), (2, 2), (3, 4), (4, 1)]
元組
「元組」定義文法為:
(元素1, 元素2, ..., 元素n)
- 小括号把所有元素綁在一起
- 逗号将每個元素一一分開
1. 建立和通路一個元組
- Python 的元組與清單類似,不同之處在于tuple被建立後就不能對其進行修改,類似字元串。
- 元組使用小括号,清單使用方括号。
- 元組與清單類似,也用整數來對它進行索引 (indexing) 和切片 (slicing)。
【例子】
t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print(t1, type(t1))
# (1, 10.31, 'python') <class 'tuple'>
print(t2, type(t2))
# (1, 10.31, 'python') <class 'tuple'>
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1[1]) # 2
print(tuple1[5:]) # (6, 7, 8)
print(tuple1[:5]) # (1, 2, 3, 4, 5)
tuple2 = tuple1[:]
print(tuple2) # (1, 2, 3, 4, 5, 6, 7, 8)
- 建立元組可以用小括号 (),也可以什麼都不用,為了可讀性,建議還是用 ()。
- 元組中隻包含一個元素時,需要在元素後面添加逗号,否則括号會被當作運算符使用。
【例子】
x = (1)
print(type(x)) # <class 'int'>
x = 2, 3, 4, 5
print(type(x)) # <class 'tuple'>
x = []
print(type(x)) # <class 'list'>
x = ()
print(type(x)) # <class 'tuple'>
x = (1,)
print(type(x)) # <class 'tuple'>
【例子】
print(8 * (8)) # 64
print(8 * (8,)) # (8, 8, 8, 8, 8, 8, 8, 8)
【例子】建立二維元組。
x = (1, 10.31, 'python'), ('data', 11)
print(x)
# ((1, 10.31, 'python'), ('data', 11))
print(x[0])
# (1, 10.31, 'python')
print(x[0][0], x[0][1], x[0][2])
# 1 10.31 python
print(x[0][0:2])
# (1, 10.31)
2. 更新和删除一個元組
【例子】
week = ('Monday', 'Tuesday', 'Thursday', 'Friday')
week = week[:2] + ('Wednesday',) + week[2:]
print(week) # ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
【例子】元組有不可更改 (immutable) 的性質,是以不能直接給元組的元素指派,但是隻要元組中的元素可更改 (mutable),那麼我們可以直接更改其元素,注意這跟指派其元素不同。
t1 = (1, 2, 3, [4, 5, 6])
print(t1) # (1, 2, 3, [4, 5, 6])
t1[3][0] = 9
print(t1) # (1, 2, 3, [9, 5, 6])
3. 元組相關的操作符
- 等号操作符:
==
- 連接配接操作符
+
- 重複操作符
*
- 成員關系操作符
、in
not in
「等号 ==」,隻有成員、成員位置都相同時才傳回True。
元組拼接有兩種方式,用「加号 +」和「乘号 *」,前者首尾拼接,後者複制拼接。
【例子】
t1 = (123, 456)
t2 = (456, 123)
t3 = (123, 456)
print(t1 == t2) # False
print(t1 == t3) # True
t4 = t1 + t2
print(t4) # (123, 456, 456, 123)
t5 = t3 * 3
print(t5) # (123, 456, 123, 456, 123, 456)
t3 *= 3
print(t3) # (123, 456, 123, 456, 123, 456)
print(123 in t3) # True
print(456 not in t3) # False
4. 内置方法
元組大小和内容都不可更改,是以隻有
count
和
index
兩種方法。
【例子】
t = (1, 10.31, 'python')
print(t.count('python')) # 1
print(t.index(10.31)) # 1
count('python') 是記錄在元組 t 中該元素出現幾次,顯然是 1 次
index(10.31) 是找到該元素在元組 t 的索引,顯然是 1
5. 解壓元組
【例子】解壓(unpack)一維元組(有幾個元素左邊括号定義幾個變量)
t = (1, 10.31, 'python')
(a, b, c) = t
print(a, b, c)
# 1 10.31 python
【例子】解壓二維元組(按照元組裡的元組結構來定義變量)
t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python
【例子】如果你隻想要元組其中幾個元素,用通配符「*」,英文叫 wildcard,在計算機語言中代表一個或多個元素。下例就是把多個元素丢給了
rest
變量。
t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c) # 1 2 5
print(rest) # [3, 4]
【例子】如果你根本不在乎 rest 變量,那麼就用通配符「*」加上下劃線「_」。
t = 1, 2, 3, 4, 5
a, b, *_ = t
print(a, b) # 1 2
字元串
1. 字元串的定義
- Python 中字元串被定義為引号之間的字元集合。
- Python 支援使用成對的 單引号 或 雙引号。
【例子】
t1 = 'i love Python!'
print(t1, type(t1))
# i love Python! <class 'str'>
t2 = "I love Python!"
print(t2, type(t2))
# I love Python! <class 'str'>
print(5 + 8) # 13
print('5' + '8') # 58
- Python 的常用轉義字元
轉義字元 | 描述 |
---|---|
| 反斜杠符号 |
| 單引号 |
| 雙引号 |
| 換行 |
| 橫向制表符(TAB) |
| 回車 |
【例子】如果字元串中需要出現單引号或雙引号,可以使用轉義符号
\
對字元串中的符号進行轉義。
print('let\'s go') # let's go
print("let's go") # let's go
print('C:\\now') # C:\now
print("C:\\Program Files\\Intel\\Wifi\\Help")
# C:\Program Files\Intel\Wifi\Help
【例子】原始字元串隻需要在字元串前邊加一個英文字母 r 即可。
print(r'C:\Program Files\Intel\Wifi\Help')
# C:\Program Files\Intel\Wifi\Help
【例子】三引号允許一個字元串跨多行,字元串中可以包含換行符、制表符以及其他特殊字元。
para_str = """這是一個多行字元串的執行個體
多行字元串可以使用制表符
TAB ( \t )。
也可以使用換行符 [ \n ]。
"""
print(para_str)
# 這是一個多行字元串的執行個體
# 多行字元串可以使用制表符
# TAB ( )。
# 也可以使用換行符 [
# ]。
para_str = '''這是一個多行字元串的執行個體
多行字元串可以使用制表符
TAB ( \t )。
也可以使用換行符 [ \n ]。
'''
print(para_str)
# 這是一個多行字元串的執行個體
# 多行字元串可以使用制表符
# TAB ( )。
# 也可以使用換行符 [
# ]。
2. 字元串的切片與拼接
- 類似于元組具有不可修改性
- 從 0 開始 (和 Java 一樣)
- 切片通常寫成
這種形式,包括「start:end
索引」對應的元素,不包括「start
索引」對應的元素。end
- 索引值可正可負,正索引從 0 開始,從左往右;負索引從 -1 開始,從右往左。使用負數索引時,會從最後一個元素開始計數。最後一個元素的位置編号是 -1。
【例子】
str1 = 'I Love LsgoGroup'
print(str1[:6]) # I Love
print(str1[5]) # e
print(str1[:6] + " 插入的字元串 " + str1[6:])
# I Love 插入的字元串 LsgoGroup
s = 'Python'
print(s) # Python
print(s[2:4]) # th
print(s[-5:-2]) # yth
print(s[2]) # t
print(s[-1]) # n
3. 字元串的常用内置方法
-
将字元串的第一個字元轉換為大寫。capitalize()
【例子】
str2 = 'xiaoxie'
print(str2.capitalize()) # Xiaoxie
-
轉換字元串中所有大寫字元為小寫。lower()
-
轉換字元串中的小寫字母為大寫。upper()
-
将字元串中大寫轉換為小寫,小寫轉換為大寫。swapcase()
【例子】
str2 = "DAXIExiaoxie"
print(str2.lower()) # daxiexiaoxie
print(str2.upper()) # DAXIEXIAOXIE
print(str2.swapcase()) # daxieXIAOXIE
-
傳回count(str, beg= 0,end=len(string))
在 string 裡面出現的次數,如果str
或者beg
指定則傳回指定範圍内end
出現的次數。str
【例子】
str2 = "DAXIExiaoxie"
print(str2.count('xi')) # 2
-
檢查字元串是否以指定子字元串endswith(suffix, beg=0, end=len(string))
結束,如果是,傳回 True,否則傳回 False。如果suffix
和beg
指定值,則在指定範圍内檢查。end
-
檢查字元串是否以指定子字元串startswith(substr, beg=0,end=len(string))
開頭,如果是,傳回 True,否則傳回 False。如果substr
和beg
指定值,則在指定範圍内檢查。end
【例子】
str2 = "DAXIExiaoxie"
print(str2.endswith('ie')) # True
print(str2.endswith('xi')) # False
print(str2.startswith('Da')) # False
print(str2.startswith('DA')) # True
-
檢測find(str, beg=0, end=len(string))
是否包含在字元串中,如果指定範圍str
和beg
,則檢查是否包含在指定範圍内,如果包含,傳回開始的索引值,否則傳回 -1。end
-
類似于rfind(str, beg=0,end=len(string))
函數,不過是從右邊開始查找。find()
【例子】
str2 = "DAXIExiaoxie"
print(str2.find('xi')) # 5
print(str2.find('ix')) # -1
print(str2.rfind('xi')) # 9
-
如果字元串中隻包含數字字元,則傳回 True,否則傳回 False。isnumeric()
【例子】
str3 = '12345'
print(str3.isnumeric()) # True
str3 += 'a'
print(str3.isnumeric()) # False
-
傳回一個原字元串左對齊,并使用ljust(width[, fillchar])
(預設空格)填充至長度fillchar
的新字元串。width
-
傳回一個原字元串右對齊,并使用rjust(width[, fillchar])
(預設空格)填充至長度fillchar
的新字元串。width
【例子】
str4 = '1101'
print(str4.ljust(8, '0')) # 11010000
print(str4.rjust(8, '0')) # 00001101
-
截掉字元串左邊的空格或指定字元。lstrip([chars])
-
删除字元串末尾的空格或指定字元。rstrip([chars])
-
在字元串上執行strip([chars])
和lstrip()
。rstrip()
【例子】
str5 = ' I Love LsgoGroup '
print(str5.lstrip()) # 'I Love LsgoGroup '
print(str5.lstrip().strip('I')) # ' Love LsgoGroup '
print(str5.rstrip()) # ' I Love LsgoGroup'
print(str5.strip()) # 'I Love LsgoGroup'
print(str5.strip().strip('p')) # 'I Love LsgoGrou'
-
找到子字元串sub,把字元串分為一個三元組partition(sub)
,如果字元串中不包含sub則傳回(pre_sub,sub,fol_sub)
。('原字元串','','')
-
類似于rpartition(sub)
方法,不過是從右邊開始查找。partition()
【例子】
str5 = ' I Love LsgoGroup '
print(str5.strip().partition('o')) # ('I L', 'o', 've LsgoGroup')
print(str5.strip().partition('m')) # ('I Love LsgoGroup', '', '')
print(str5.strip().rpartition('o')) # ('I Love LsgoGr', 'o', 'up')
-
把 将字元串中的replace(old, new [, max])
替換成old
,如果new
指定,則替換不超過max
次。max
【例子】
str5 = ' I Love LsgoGroup '
print(str5.strip().replace('I', 'We')) # We Love LsgoGroup
-
不帶參數預設是以空格為分隔符切片字元串,如果split(str="", num)
參數有設定,則僅分隔num
個子字元串,傳回切片後的子字元串拼接的清單。num
【例子】
str5 = ' I Love LsgoGroup '
print(str5.strip().split()) # ['I', 'Love', 'LsgoGroup']
print(str5.strip().split('o')) # ['I L', 've Lsg', 'Gr', 'up']
【例子】
u = "www.baidu.com.cn"
# 使用預設分隔符
print(u.split()) # ['www.baidu.com.cn']
# 以"."為分隔符
print((u.split('.'))) # ['www', 'baidu', 'com', 'cn']
# 分割0次
print((u.split(".", 0))) # ['www.baidu.com.cn']
# 分割一次
print((u.split(".", 1))) # ['www', 'baidu.com.cn']
# 分割兩次
print(u.split(".", 2)) # ['www', 'baidu', 'com.cn']
# 分割兩次,并取序列為1的項
print((u.split(".", 2)[1])) # baidu
# 分割兩次,并把分割後的三個部分儲存到三個變量
u1, u2, u3 = u.split(".", 2)
print(u1) # www
print(u2) # baidu
print(u3) # com.cn
【例子】去掉換行符
c = '''say
hello
baby'''
print(c)
# say
# hello
# baby
print(c.split('\n')) # ['say', 'hello', 'baby']
【例子】
string = "hello boy<[www.baidu.com]>byebye"
print(string.split('[')[1].split(']')[0]) # www.baidu.com
print(string.split('[')[1].split(']')[0].split('.')) # ['www', 'baidu', 'com']
-
按照行('\r', '\r\n', \n')分隔,傳回一個包含各行作為元素的清單,如果參數splitlines([keepends])
為 False,不包含換行符,如果為 True,則保留換行符。keepends
【例子】
str6 = 'I \n Love \n LsgoGroup'
print(str6.splitlines()) # ['I ', ' Love ', ' LsgoGroup']
print(str6.splitlines(True)) # ['I \n', ' Love \n', ' LsgoGroup']
-
建立字元映射的轉換表,第一個參數是字元串,表示需要轉換的字元,第二個參數也是字元串表示轉換的目标。maketrans(intab, outtab)
-
根據參數translate(table, deletechars="")
給出的表,轉換字元串的字元,要過濾掉的字元放到table
參數中。deletechars
【例子】
str7 = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str7.maketrans(intab, outtab)
print(trantab) # {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}
print(str7.translate(trantab)) # th3s 3s str3ng 2x1mpl2....w4w!!!
4. 字元串格式化
-
格式化函數format
【例子】
str8 = "{0} Love {1}".format('I', 'Lsgogroup') # 位置參數
print(str8) # I Love Lsgogroup
str8 = "{a} Love {b}".format(a='I', b='Lsgogroup') # 關鍵字參數
print(str8) # I Love Lsgogroup
str8 = "{0} Love {b}".format('I', b='Lsgogroup') # 位置參數要在關鍵字參數之前
print(str8) # I Love Lsgogroup
str8 = '{0:.2f}{1}'.format(27.658, 'GB') # 保留小數點後兩位
print(str8) # 27.66GB
- Python 字元串格式化符号
符 号 | 描述 |
---|---|
%c | 格式化字元及其ASCII碼 |
%s | 格式化字元串,用str()方法處理對象 |
%r | 格式化字元串,用rper()方法處理對象 |
%d | 格式化整數 |
%o | 格式化無符号八進制數 |
%x | 格式化無符号十六進制數 |
%X | 格式化無符号十六進制數(大寫) |
%f | 格式化浮點數字,可指定小數點後的精度 |
%e | 用科學計數法格式化浮點數 |
%E | 作用同%e,用科學計數法格式化浮點數 |
%g | 根據值的大小決定使用%f或%e |
%G | 作用同%g,根據值的大小決定使用%f或%E |
【例子】
print('%c' % 97) # a
print('%c %c %c' % (97, 98, 99)) # a b c
print('%d + %d = %d' % (4, 5, 9)) # 4 + 5 = 9
print("我叫 %s 今年 %d 歲!" % ('小明', 10)) # 我叫 小明 今年 10 歲!
print('%o' % 10) # 12
print('%x' % 10) # a
print('%X' % 10) # A
print('%f' % 27.658) # 27.658000
print('%e' % 27.658) # 2.765800e+01
print('%E' % 27.658) # 2.765800E+01
print('%g' % 27.658) # 27.658
text = "I am %d years old." % 22
print("I said: %s." % text) # I said: I am 22 years old..
print("I said: %r." % text) # I said: 'I am 22 years old.'
- 格式化操作符輔助指令
符号 | 功能 |
---|---|
| m 是顯示的最小總寬度,n 是小數點後的位數(如果可用的話) |
| 用作左對齊 |
| 在正數前面顯示加号( + ) |
| 在八進制數前面顯示零('0'),在十六進制前面顯示'0x'或者'0X'(取決于用的是'x'還是'X') |
顯示的數字前面填充'0'而不是預設的空格 |
【例子】
print('%5.1f' % 27.658) # ' 27.7'
print('%.2e' % 27.658) # 2.77e+01
print('%10d' % 10) # ' 10'
print('%-10d' % 10) # '10 '
print('%+d' % 10) # +10
print('%#o' % 10) # 0o12
print('%#x' % 108) # 0x6c
print('%010d' % 5) # 0000000005