Jupyter Notebook 形式で文字列メソッドを用途別に整理し、各セルで出力例を確認できるノートブックを作成しました。
このままコピーして .ipynb に変換すれば実行可能。
内容には、基本的な文字列メソッドの動作確認と練習問題も含まれています。
# Jupyter Notebook形式: Python文字列メソッド 練習ノート
# %%
# # Python文字列メソッド 練習ノート
# このノートブックでは、文字列メソッドを用途別に確認し、実際にコードを実行して動作を確認できます。
# %%
# ## 1. 大文字・小文字の変換
s = "hello world"
print("Original:", s)
print("lower():", s.lower())
print("upper():", s.upper())
print("capitalize():", s.capitalize())
print("title():", s.title())
print("swapcase():", s.swapcase())
# %%
# ## 2. 空白・改行の除去
s = " Hello World "
print("Original:'{}'".format(s))
print("strip(): '{}'").format(s.strip())
print("lstrip(): '{}'").format(s.lstrip())
print("rstrip(): '{}'").format(s.rstrip())
# %%
# ## 3. 文字列の分割・結合
s = "apple,banana,cherry"
print("split(','):", s.split(","))
items = s.split(",")
print("join with '-':", "-".join(items))
# %%
# ## 4. 検索・判定
s = "banana"
print("find('na'):", s.find("na"))
print("rfind('na'):", s.rfind("na"))
print("count('na'):", s.count("na"))
print("startswith('ba'):", s.startswith("ba"))
print("endswith('na'):", s.endswith("na"))
# %%
# ## 5. 置換・加工
s = "apple banana apple"
print("Original:", s)
print("replace('apple', 'orange'):", s.replace("apple", "orange"))
# %%
# ## 6. 文字の種類チェック
s1 = "abc"
s2 = "123"
s3 = "abc123"
s4 = " "
print("'abc'.isalpha():", s1.isalpha())
print("'123'.isdigit():", s2.isdigit())
print("'abc123'.isalnum():", s3.isalnum())
print("' '.isspace():", s4.isspace())
# %%
# ## 7. 配置・整形
print("center():", "Hi".center(6, '-'))
print("ljust():", "Hi".ljust(6, '.'))
print("rjust():", "Hi".rjust(6, '.'))
print("zfill():", "42".zfill(5))
# %%
# ## 8. 文字列フォーマット
name = "Alice"
age = 30
print(f"f-string: {name}さんは{age}歳です")
print("str.format(): {}さんは{}歳です".format(name, age))
print("str.format_map(): {name}さんは{age}歳です".format_map({'name':name,'age':age}))
# %%
# ## 9. エスケープシーケンス
print("改行\n次の行")
print("タブ\tタブ")
print(r"C:\Users\Name")
# %%
# ## 練習問題
# Q1. " Python " を前後の空白を取り除き大文字に変換
s = " Python "
print(s.strip().upper())
# %%
# Q2. "A,B,C" を split() で分割して join() で "A-B-C" に変換
s = "A,B,C"
print("-".join(s.split(",")))
# %%
# Q3. "apple banana apple" の "apple" を "orange" に置換して count("apple") の結果を出力
s = "apple banana apple"
print(s.replace("apple","orange"), s.count("apple"))
# %%
# Q4. "Python" が "Py" で始まり "on" で終わるか判定
s = "Python"
print(s.startswith("Py"), s.endswith("on"))
Python