在 Python 程式設計中,字串 (str) 是一種用於表示文字資料的序列型別。本文將深入探討 Python 字串的各個方面,包括定義、表示方式、基本操作、常用方法、字串格式化,以及實際應用。
什麼是字串 (str)?
字串是由零個或多個字元組成的序列。在 Python 中,字串屬於 str
型別,並且是不可變的 (immutable),這意味著一旦建立後,就不能修改其內容 (但可以建立新的字串)。
字串的表示方式
Python 中有多種方式可以表示字串:
- 單引號 ('):
'Hello, world!'
- 雙引號 ("):
"Hello, world!"
- 三引號 (''' 或 """): 用於表示多行字串,或包含單引號/雙引號的字串。
# 單引號
s1 = 'Hello, Python!'
# 雙引號
s2 = "Hello, Python!"
# 三引號 (多行字串)
s3 = '''This is a
multi-line string.'''
s4 = """This string contains 'single quotes' and "double quotes"."""
print(type(s1)) # 輸出: <class 'str'>
使用建議: 單引號和雙引號可以互換使用,但建議在同一個專案中保持一致的風格。三引號通常用於表示多行文字或包含引號的字串。
字串的基本操作
Python 提供了豐富的字串操作:
- 拼接 (+): 將兩個或多個字串連接起來。
- 重複 (*): 將字串重複多次。
- 索引 ([]): 存取字串中的特定字元 (索引從 0 開始)。
- 切片 ([start:end:step]): 提取字串的一部分。
- 計算長度 (len()): 取得字串的長度 (字元數)。
s1 = "Hello"
s2 = "World"
# 拼接
s3 = s1 + " " + s2 # 輸出: Hello World
print(s3)
# 重複
s4 = s1 * 3 # 輸出: HelloHelloHello
print(s4)
# 索引
print(s1[0]) # 輸出: H
print(s1[-1]) # 輸出: o (負數索引表示從後面數)
# 切片
print(s1[1:4]) # 輸出: ell (從索引 1 到 4 (不含 4))
print(s1[::2]) # 輸出: Hlo (每隔 2 個字元取一個)
print(s1[::-1]) # 輸出: olleH (反轉字串)
#長度
print(len(s1)) #輸出: 5
字串的常用方法
Python 的字串物件提供了許多內建方法,可以方便地進行各種字串處理:
lower()
,upper()
: 轉換為小寫/大寫。strip()
,lstrip()
,rstrip()
: 去除空白 (或指定字元)。startswith(prefix)
,endswith(suffix)
: 檢查是否以指定字串開頭/結尾。find(sub)
,index(sub)
: 尋找子字串 (找不到時,find
返回 -1,index
引發ValueError
)。replace(old, new)
: 替換子字串。split(sep)
: 以指定分隔符號分割字串,返回串列。join(iterable)
: 將可迭代物件 (例如串列) 中的字串連接起來。count(sub)
: 計算指定字串出現幾次。
text = " Hello, World! "
print(text.lower()) # 輸出: hello, world!
print(text.upper()) # 輸出: HELLO, WORLD!
print(text.strip()) # 輸出: Hello, World!
print(text.startswith(" ")) # 輸出: True
print(text.find("World")) # 輸出: 10
print(text.replace("Hello", "Hi")) # 輸出: Hi, World!
print(text.split(",")) # 輸出: [' Hello', ' World! ']
words = ['This', 'is', 'a', 'sentence']
print(' '.join(words)) # 輸出: This is a sentence
print(text.count('l')) #輸出: 3
字串格式化
將變數的值插入到字串中的過程,稱為字串格式化。Python 提供了多種字串格式化方法:
- f-string (Formatted String Literals, 推薦): 最現代、最簡潔的方式,在字串前加上
f
或F
,並在字串中使用大括號{}
插入變數或表達式。 str.format()
方法: 使用{}
作為佔位符,並在format()
方法中傳入對應的值。%
運算符 (舊式): 使用%s
、%d
、%f
等格式化符號,並在%
後面傳入對應的值 (類似 C 語言的printf
)。
name = "Alice"
age = 30
# f-string (推薦)
message = f"My name is {name} and I am {age} years old."
print(message)
# str.format()
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
# % 運算符 (舊式)
message = "My name is %s and I am %d years old." % (name, age)
print(message)
字串的應用
- 文字處理: 文件分析、自然語言處理、網頁爬蟲等。
- 資料輸入/輸出: 格式化輸出、解析輸入資料。
- 使用者介面: 顯示訊息、提示、錯誤等。
- 網路程式設計: 傳輸和處理文字資料。
總結
Python 的字串 (str) 型別是一種功能強大且用途廣泛的資料型別,提供了豐富的操作和方法。 熟悉字串的各種特性,對於高效的 Python 程式設計至關重要。