文字列の操作

開発者のためのPython入門

Jasmin Ludolf

Senior Data Science Content Developer

文字列はどこにでもある!

Hello written with string

  • メッセージ表示
  • テキスト入力の処理
  • ファイル名
  • 出力の書式設定
  • データ処理
1 ChatGPTで生成された画像
開発者のためのPython入門

Python はシングルクォートとダブルクォートを認識する

# This works
ingredient_name = 'San Marzano tomatoes'

# This also works
ingredient_name = "San Marzano tomatoes"
  • ' = アポストロフィ = シングルクォート
開発者のための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入門

メソッド

  • メソッド = 特定のデータ型でのみ使用できる関数

  • 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入門

大文字・小文字の変更

  • メールアドレスのようなユーザー入力を標準化する
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...