第 7 章 字串
(1) Python 資料型態
∗ Python 內建的資料型態
▸ 原始資料型態 (Primitive data type):int, float, bool
✶ 型態單一,資料不可再分割
▸ 集合資料型態 (Collection data type),屬較高階的資料結構:str, list, dictionary, ...
✶ 由許多小部份組成,資料可再分割
∗ Python 物件
▸ Python 裡的所有東西都是物件 (Everything in python is an object),包括數字、字串、函式、資料結構、類別、模組等
▸ Python 提供各類物件相關的「方法」(Method) 可以呼叫,例如字串:
x = 'Hello world'
print(x.upper()) # 呼叫字串物件的 upper() 方法,將字元改為大寫
(2) 字串簡介
∗ 字串 (String)
▸ 由一串字元組成,例如:'Hello world'
▸ 建立空字串:
emptyString = ''
▸ 字串與字串相加 (運算子為 +):將兩個字串連接
hello = 'Hello'
world = 'world'
print(hello + ' ' + world)
∗ 字串中各個字元的位置
▸ 字串中的字元由左向右排列,位置從 0 開始由左向右遞增,亦可從 -1 開始由右向左遞減,例如:
hello = 'Hello world'
✶ 可利用索引運算子 (Index operator) 取出字串中的某字元,索引運算子為內含數字 (即「索引」) 之方括號,例如: hello[8] 或 hello[-3] 都是 'r'
✶ 索引也可以是個表示式,例如:
x = 12 y = 3 print(hello[x-2*y]) # 'w'
(3) 字串方法
∗ 字串是物件 (Object)
▸ 每一個字串物件都有它的屬性 (Attribute) 以及可以呼叫的方法 (Method)
▸ 使用點符號存取屬性及方法,例如:
hello = 'Hello world'
print(hello.upper())
print(hello.lower())
✶ upper() 將所有字元改為大寫,然後回覆一個新字串
✶ lower() 將所有字元改為小寫,然後回覆一個新字串
▸ 字串常用的方法:
語法:<theString>.<method>(),例如:
a = 'Hello world' a = a.upper() # HELLO WORLD
方法 | 說明 |
---|---|
.upper() | 回覆一個全大寫的字串 |
.lower() | 回覆一個全小寫的字串 |
.capitalize() | 回覆一個首字大寫的字串 |
.split(<x>) | 以 <x> 字元分解字串,回覆一個串列 若無參數, 則預設字元為空白 |
.strip() | 回覆一個左右均無空白的字串 |
.lstrip() | 回覆一個左邊無空白的字串 |
.rstrip() | 回覆一個右邊無空白的字串 |
.count(<item>) | 回覆 <item> 子字串出現的次數 |
.replace(<old>, <new>) | 將 <old> 子字串置換為 <new> |
.center(<width>) | 在 <width> 寬度裡置中 |
.ljust(<width>) | 在 <width> 寬度裡靠左對齊 |
.rjust(<width>) | 在 <width> 寬度裡靠右對齊 |
.find(<item>) | 尋找出現在最左邊的 <item> 字串,如果找不到就回覆 -1 |
.rfind(<item>) | 尋找出現在最右邊的 <item> 字串,如果找不到就回覆 -1 |
.index(<item>) | 同 find(), 但如果找不到就發出執行錯誤 |
.index(<item>) | 同 find(), 但如果找不到就發出執行錯誤 |
.isdigit() | 是否是數字字串 |
∗ 字串長度:回覆字串裡的字元數量
fruit = 'Banana'
print(len(fruit))
∗ 字串切片 (Slicing):從字串中切出一段子字串
hello = 'Hello world'
print(hello[0:5]) # 從 0 到 4 切出子字串
print(hello[:5]) # 從 0 開始,第一個索引可以省略
print(hello[5:]) # 到最後結束,第二個索引可以省略
print(hello[:]) # 從 0 開始到最後結束,兩個索引都可以省略
print(hello[6:11]) # 從 6 到 10 切出子字串
print(hello[6:100]) # 第二個索引超出範圍:不會有錯誤訊息
∗ 字串內容是不可改變的 (Immutable)
hello = 'Hello world'
hello[0] = 'h'
print(hello)
▸ 解決方案:利用產生新字串方式來改變字串內容
hello = 'Hello world'
hello = 'h' + hello[1:]
print(hello)
∗ in 運算子:檢查字串中是否有某個子字串
print('p' in 'apple')
print('i' in 'apple')
print('ap' in 'apple')
print('pa' in 'apple')
print('pa' not in 'apple')