好的,我會將 Python 代碼與其對應的繁體中文翻譯一起呈現,以便更清楚地理解概念與實際應用。
Python 初學者教程 2:字串 - 處理文字資料(摘要與程式碼)
Python Tutorial for Beginners 2: Strings - Working with Textual Data (Summary & Code)
1. 介紹字串 (00:02 - 00:31)
1. Introduction to Strings (00:02 - 00:31)
message = "Hello, World!"
print(message)
解釋:
- 在 Python 中,字串(String)用於表示文字資料。
print(message)會輸出變數message的內容,即"Hello, World!"。
2. 變數命名規範 (00:31 - 01:28)
2. Variable Naming Conventions (00:31 - 01:28)
my_message = "Hello, Python!"
print(my_message)
解釋:
- 變數名稱應使用小寫,單詞之間用底線
_分隔,例如my_message。 print(my_message)會輸出"Hello, Python!"。
3. 字串語法與引號 (02:02 - 03:38)
3. String Syntax and Quotes (02:02 - 03:38)
message1 = 'I\'m learning Python!' # 使用反斜線(\)來轉義單引號
message2 = "I'm learning Python!" # 直接使用雙引號
print(message1)
print(message2)
解釋:
- 如果字串內有單引號
',可以使用雙引號"包圍字串來避免錯誤。 - 也可以使用反斜線
\來轉義單引號,確保字串正常運行。
4. 多行字串 (03:38 - 04:17)
4. Multi-line Strings (03:38 - 04:17)
long_message = """這是一個
多行字串
範例"""
print(long_message)
解釋:
- 使用三重引號
"""或'''來表示多行字串。 - 輸出結果:
這是一個 多行字串 範例
5. 字串索引與切片 (04:17 - 07:40)
5. String Indexing and Slicing (04:17 - 07:40)
message = "Python"
print(message[0]) # 輸出 'P'
print(message[-1]) # 輸出 'n'
print(message[0:4]) # 輸出 'Pyth'
print(message[:4]) # 輸出 'Pyth' (省略起始索引)
print(message[2:]) # 輸出 'thon' (省略結束索引)
解釋:
message[0]取得第一個字元'P',message[-1]取得最後一個字元'n'。message[0:4]取得從索引0到3(不包含4)的部分,即'Pyth'。
6. 字串方法 (08:13 - 10:53)
6. String Methods (08:13 - 10:53)
message = "Hello World"
print(len(message)) # 輸出 11
print(message.lower()) # 輸出 'hello world'
print(message.upper()) # 輸出 'HELLO WORLD'
print(message.count('l')) # 輸出 3
print(message.find('World')) # 輸出 6
print(message.replace('World', 'Python')) # 輸出 'Hello Python'
解釋:
len(message)回傳字串長度。.lower()和.upper()轉換字串大小寫。.count('l')計算字串內'l'出現的次數。.find('World')回傳'World'在字串中的索引位置。.replace('World', 'Python')替換"World"為"Python"。
7. 字串連接 (10:53 - 14:47)
7. String Concatenation (10:53 - 14:47)
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # 輸出 'John Doe'
解釋:
+用於連接字串,這裡將first_name和last_name連接,並加上" "空格。
8. 格式化字串 (14:47 - 16:23)
8. Formatted Strings (14:47 - 16:23)
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message) # 輸出 'My name is Alice and I am 25 years old.'
解釋:
- 使用
.format()來插入變數值進入字串{}佔位符中。
9. 進階字串格式化 (16:23 之後)
9. Advanced String Formatting (Beyond 16:23)
name = "Bob"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message) # 輸出 'My name is Bob and I am 30 years old.'
解釋:
f""字串(f-string)是一種更直觀的格式化方式,{變數}會自動替換成變數的值。
總結
- 字串在 Python 中可以使用
'或"定義。 - 可以使用
+來連接字串,或使用format()及f-string來格式化字串。 - 字串支援索引與切片,允許存取特定字元或子字串。
- Python 內建許多字串方法,例如
.lower()、.upper()、.replace()等。
這些概念是學習 Python 的基礎,掌握後能夠更靈活地處理文字資料! 🚀
沒有留言:
張貼留言