Python文字列操作の核心メソッドと型変換

メソッド 機能概要 使用例 結果
upper() 文字列をすべて大文字に変換 "python".upper() "PYTHON"
lower() 文字列をすべて小文字に変換 "PyThOn".lower() "python"
startswith(prefix) 指定接頭辞で始まるか判定(ブール値) "data-engineer".startswith("data") True
endswith(suffix) 指定接尾辞で終わるか判定(ブール値) "report.csv".endswith(".csv") True
isdigit() 文字列が数値文字のみ(0–9)で構成されているか "4567".isdigit() True
strip([chars]) 両端の空白・改行・タブを除去(引数で指定可能) " \t\n clean \n\t ".strip() "clean"
join(iterable) イテラブル内の要素を指定区切り文字で連結 "_".join(["alpha", "beta", "gamma"]) "alpha_beta_gamma"
split(sep=None, maxsplit=-1) 区切り文字で分割 → リスト。sep省略時は空白類で分割 "a,b,c,d".split(",") ["a", "b", "c", "d"]
find(sub) 部分文字列の先頭インデックスを返す(存在しない場合は−1) "programming".find("gram") 3
index(sub) 部分文字列の位置を返す(存在しない場合はValueError) "programming".index("pro") 0
count(sub) 部分文字列の出現回数をカウント "banana".count("a") 3
replace(old, new, count=-1) 指定文字列を置換(countで最大置換数を制限可能) "apple apple apple".replace("apple", "orange", 2) "orange orange apple"

以下は、代表的な文字列操作の実装例です:

# 大文字・小文字変換
source = "DataScience"
uppercase_form = source.upper()
lowercase_form = source.lower()
print(f"元: {source} → 大文字: {uppercase_form}, 小文字: {lowercase_form}")

# 接頭辞・接尾辞チェック
filename = "config.json"
print(f"{filename} は '.json' で終わる?→ {filename.endswith('.json')}")
print(f"{filename} は 'config' で始まる?→ {filename.startswith('config')}")

# 数字判定とクリーニング
raw_input = "  8675309  \n\t"
if raw_input.strip().isdigit():
    numeric_value = int(raw_input.strip())
    print(f"整数として解釈可能: {numeric_value}")

# 文字列分割と再構成
tags = "backend,api,rest,fastapi"
tag_list = tags.split(",")
formatted_tags = " | ".join(tag_list)
print(f"タグ一覧: {formatted_tags}")

# 部分文字列検索と置換
log_line = "[ERROR] Connection timeout after 5s"
error_position = log_line.find("[ERROR]")
safe_log = log_line.replace("[ERROR]", "[INFO]", 1)
print(f"エラー位置: {error_position}, 更新後: {safe_log}")

基本型間の変換

文字列と数値などの型変換は、データ処理の基礎です:

# 文字列 → 整数/浮動小数点数
age_str = "28"
height_str = "175.5"

age_int = int(age_str)          # → 28
height_float = float(height_str) # → 175.5

# 数値 → 文字列
pi_str = str(3.14159265)
counter_str = str(42)

print(f"年齢型: {type(age_int).__name__}, 身長型: {type(height_float).__name__}")
print(f"円周率文字列: '{pi_str}', カウンター文字列: '{counter_str}'")

タグ: Python string-methods type-conversion strip split

6月12日 20:41 投稿