處理字串

Python 入門(開發者向)

Jasmin Ludolf

Senior Data Science Content Developer

字串無所不在!

以字串寫成的 Hello

  • 顯示訊息
  • 處理文字輸入
  • 檔名
  • 輸出格式化
  • 處理資料
1 Image generated by ChatGPT
Python 入門(開發者向)

Python 認得單引號與雙引號

# This works
ingredient_name = 'San Marzano tomatoes'

# This also works
ingredient_name = "San Marzano tomatoes"
  • ' = apostrophe = single quote
Python 入門(開發者向)

雙引號的優勢

# Single quote string variable containing an apostrophe
ingredient_name = 'Chef's special seasoning'
print(ingredient_name)
SyntaxError: invalid syntax.
# Double quote string variable containing an apostrophe
ingredient_name = "Chef's special seasoning"
print(ingredient_name)
Chef's special seasoning
Python 入門(開發者向)

句子與段落

recipe_step = "Heat olive oil in a large pan and sauté garlic until fragrant"
Python 入門(開發者向)

多行字串

# Create a string variable over multiple lines
recipe_instructions = """1. Bring a large pot of salted water to boil and cook pasta
2. Heat olive oil in a pan and sauté minced garlic until fragrant
3. Add chopped tomatoes and simmer for 10 minutes
4. Toss cooked pasta with tomato sauce and fresh basil leaves
"""
  • """text""":多行字串
    • 提升可讀性
    • 用於文件說明
    • 適合較長文字,如步驟或錯誤訊息
Python 入門(開發者向)

方法(Methods)

  • 方法=只供特定資料型別使用的函式

  • str 方法

    • 標準化輸入,或轉換文字
# Calling a string method
string_variable.method()
Python 入門(開發者向)

取代字串的一部分

  • .replace(text_to_be_replaced, text_to_change_it_to)
welcome_message = "Welcome to the recipe scaler, George"

welcome_message = welcome_message.replace("George", "John")

print(welcome_message)
Welcome to the recipe scaler, John
Python 入門(開發者向)

變更大小寫

  • 標準化使用者輸入,如 email
ingredient_name = "Basil Leaves"

# Convert to lowercase ingredient_name = ingredient_name.lower() print(ingredient_name)
basil leaves
# Change to uppercase
ingredient_name = ingredient_name.upper()
print(ingredient_name)
BASIL LEAVES
Python 入門(開發者向)

一起來練習吧!

Python 入門(開發者向)

Preparing Video For Download...