文字列: テキスト処理
f-string で簡潔に。スライスで柔軟に操作。
f-string
f"..." 形式の文字列補間。
スライス
[start:end] で部分文字列。
メソッド
文字列に対する操作関数。
文字列基礎
Pythonの文字列は「シーケンス(順番のあるデータ)」の一種です。リストと同じようにスライス(切り出し)やループが使えますが、中身を直接書き換える代入(`s[0] = "A"`)はエラーになります。
# 文字列リテラルsingle = 'Hello'double = "World"multi = """複数行文字列"""
# f-string (Python 3.6+)name = "Alice"age = 30greeting = f"Hi, {name}! You are {age} years old."
# 文字列操作s = "hello"s.upper() # "HELLO"s.replace("l", "L") # "heLLo"s.split() # ["hello"]" ".join(["a", "b"]) # "a b"Bad
# ❌ Bad: + で連結result = "Name: " + name + ", Age: " + str(age)Good
# ✅ Good: f-stringresult = f"Name: {name}, Age: {age}"高度な操作
# スライスs = "Python"s[0:2] # "Py"s[-2:] # "on"s[::-1] # "nohtyP" (逆順)
# 書式設定f"{3.14159:.2f}" # "3.14"f"{42:05d}" # "00042"f"{1000:,}" # "1,000"
# メソッド" hello ".strip() # "hello""hello".startswith("he") # True"hello".find("l") # 2"a,b,c".split(",") # ["a", "b", "c"]
# 正規表現import rere.findall(r"\d+", "abc123def456") # ["123", "456"] Tip: f-string 内で式も書ける: f"{x + y = }"
合格ライン
f-string を使える
スライスで部分文字列を取れる
演習課題
課題1: f-string
f-string で変数を埋め込んでください。
課題2: スライス
スライスで部分文字列を取得してください。