在 Python 中的字串操作

在 Python 中的字串操作

本文介紹了在 Python 中的字串操作。

你將學習各種字串操作,例如創建與連接字串、搜索與替換字串,並配有代碼範例。

YouTube Video

在 Python 中的字串操作

在 Python 中有多種操作字串的方法。以下是常用字串操作的介紹。

創建字串

在 Python 中,字串可以使用單引號(')、雙引號("),或是三重引號('''""")來建立。

1single_quoted = 'Hello'
2double_quoted = "World"
3multi_line = '''This is
4a multi-line
5string'''
6
7print(single_quoted)
8print(double_quoted)
9print(multi_line)
  • 此程式碼演示如何在 Python 中使用單引號、雙引號和三引號來建立和顯示字串。

字串連接

要連接字串,可以使用 + 操作符、f-stringsstr.format 方法。

 1# + operator
 2name = "John"
 3greeting = "Hello, " + name + "!"
 4print(greeting)
 5
 6# f-string (available in Python 3.6 and above)
 7greeting_f = f"Hello, {name}!"
 8print(greeting_f)
 9
10# str.format method
11greeting_format = "Hello, {}!".format(name)
12print(greeting_format)
  • 此程式碼展示如何在 Python 中使用 + 運算子、f-string 以及 str.format 方法來串接字串。

重複字串

要重複字串,可以使用 * 操作符。

1repeat = "ha" * 3  # Result: "hahaha"
2print(repeat)
  • 此程式碼演示如何在 Python 中使用 * 運算子重複字串。

字串的長度

要獲取字串的長度,可以使用 len 函數。

1name = "John"
2greeting = "Hello, " + name + "!"
3
4# Returns the length of the string greeting
5length = len(greeting)
6print(length)
  • 此程式碼展示如何在 Python 中使用 len 函式取得字串的長度。

索引和切片

可以使用索引或切片來獲取字串中的特定字符或子字串。

 1word = "Python"
 2
 3first_char = word[0]    # P
 4last_char = word[-1]    # n
 5print(first_char)
 6print(last_char)
 7
 8# Slice
 9sliced_word = word[1:4] # yth
10reversed_word = word[::-1] # nohtyP
11print(sliced_word)
12print(reversed_word)
  • 此程式碼演示如何在 Python 中使用索引與切片來取得字串中特定的字元或子字串。

處理每個字元

由於字串被視為序列型別,因此可以使用 for 迴圈來處理每個字元。

1text = "Python"
2
3# Iterate each character
4for char in text:
5    print(char)
  • {^ i18n_speak このコードは、文字列 Python を1文字ずつ取り出して順番に表示する方法を示しています。^}

在字串中搜索與替換

可以使用 str.findstr.replace 方法在字串中搜索與替換。

1sentence = "She sells sea shells on the sea shore."
2
3# Returns the index of the first occurrence of "sea": 10
4index = sentence.find("sea")
5print(index)
6
7# Replace "sea" with "ocean"
8replaced_sentence = sentence.replace("sea", "ocean")
9print(replaced_sentence)
  • 此程式碼展示如何在 Python 中使用 str.find 方法搜尋字串,以及使用 str.replace 方法取代字串。

字串大小寫轉換

要將字串轉換為大寫或小寫,可以使用 str.upperstr.lowerstr.capitalizestr.title 方法。

 1text = "hello world"
 2upper_text = text.upper()       # "HELLO WORLD"
 3lower_text = text.lower()       # "hello world"
 4capitalized_text = text.capitalize() # "Hello world"
 5title_text = text.title()       # "Hello World"
 6
 7print(upper_text)
 8print(lower_text)
 9print(capitalized_text)
10print(title_text)
  • 此程式碼演示如何在 Python 中將字串轉換為全大寫、全小寫以及標題大小寫。

分割與連接字串

要通過特定的分隔符分割字串,可以使用 str.split 方法;要連接列表元素,可以使用 str.join 方法。

1csv = "apples,bananas,cherries"
2fruits = csv.split(",")  # ["apples", "bananas", "cherries"]
3joined_fruits = ", ".join(fruits)  # "apples, bananas, cherries"
4
5print(fruits)
6print(joined_fruits)
  • 此程式碼展示如何在 Python 中使用 str.split 分割字串,以及使用 str.join 將串列元素連接成字串。

去除空白字符

要去除字串中的空白字符,可以使用 str.stripstr.lstripstr.rstrip 方法。

1whitespace = "   hello   "
2stripped = whitespace.strip()   # "hello"
3lstripped = whitespace.lstrip() # "hello   "
4rstripped = whitespace.rstrip() # "   hello"
5
6print(stripped)
7print(lstripped)
8print(rstripped)
  • 此程式碼演示如何在 Python 中使用 str.stripstr.lstripstr.rstrip 移除字串左右兩側或任一側的空白字元。

總結

通過結合這些操作,可以在 Python 中執行各種字串操作。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video