12.1 方法清單
在 Python 中,字串型別資料擁有豐富的方法集合,讓處理字串變得輕鬆而強大。以下是
string
類別的一些常用方法:
方法 | 描述 |
---|---|
strip() |
移除字串開頭和結尾的空格。 |
lower() |
將字串中所有字元轉換為小寫。 |
upper() |
將字串中所有字元轉換為大寫。 |
replace(old, new) |
將所有出現的子字串 old 替換為子字串 new 。 |
split(separator) |
使用指定的分隔符將字串分割成子字串清單。 |
join(iterable) |
使用分隔符字串將字串集合合併成一個字串。 |
find(substring) |
返回子字串的第一個出現索引,如果未找到則返回 -1 。
|
index(substring) |
返回子字串的第一個出現索引,如果未找到則拋出例外。 |
format() |
格式化字串,替換大括號內的值。 |
startswith(prefix) |
檢查字串是否以子字串 prefix 開頭。 |
endswith(suffix) |
檢查字串是否以子字串 suffix 結尾。 |
請注意,str
型別物件在創建後不能更改。所有更改字串的函數實際上是返回新物件。舊物件保持不變。
12.2 最受歡迎的方法
讓我們來看看一些最簡單且受歡迎的方法。
方法 strip():
移除字串開頭和結尾的空格。
text = " hello world! "
cleaned_text = text.strip()
print(cleaned_text) # 輸出: "hello world!"
方法 lower()
:
將字串中所有字元轉換為小寫。
text = "Hello World!"
lower_text = text.lower()
print(lower_text) # 輸出: "hello world!"
方法 upper()
:
將字串中所有字元轉換為大寫。
text = "Hello World!"
upper_text = text.upper()
print(upper_text) # 輸出: "HELLO WORLD!"
方法 split(separator)
:
使用指定的分隔符將字串分割成子字串清單。
text = "one,two,three"
parts = text.split(',')
print(parts) # 輸出: ['one', 'two', 'three']
方法 join(iterable)
:
使用分隔符字串將字串集合合併成一個字串。
parts = ['one', 'two', 'three']
joined_text = ','.join(parts)
print(joined_text) # 輸出: "one,two,three"
注意!
請注意,join()
方法是由分隔符字串呼叫的!
這些方法是用於處理和操作 Python 中文本資料的主要工具。
12.3 子字串的搜索與替換
還有一些流行的方法用於在字串中搜索和替換子字串。
方法 find(substring)
:
返回子字串在字串中的第一個出現索引,如果未找到則返回 -1
。
text = "hello world"
index = text.find("world")
print(index) # 輸出: 6
方法 index(substring)
:
類似於 find
,但如果未找到子字串則拋出例外 ValueError
。
text = "hello world"
try:
index = text.index("world")
print(index) # 輸出: 6
except ValueError:
print("Substring not found")
方法 replace(old, new)
:
將所有出現的子字串 old
替換為子字串 new
。
text = "hello world"
replaced_text = text.replace("world", "everyone")
print(replaced_text) # 輸出: "hello everyone"
方法 startswith(prefix)
:
檢查字串是否以指定的前綴開頭。
text = "hello world"
print(text.startswith("hello")) # 輸出: True
方法 endswith(suffix)
:
檢查字串是否以指定的後綴結尾。
text = "hello world"
print(text.endswith("world")) # 輸出: True
這些方法非常有用於字串中的各種搜索、替換和檢查操作,簡化了文本資料的處理。
GO TO FULL VERSION