Python:Python の文字列:スライス・エスケープ・組み込みメソッド
Python•文字列

Python の文字列:スライス・エスケープ・組み込みメソッド

split()、join()、strip()、replace()、f 文字列、および文字列スライスを使ったテキスト操作を学びます。

構文

text = "Sample String" formatted = f"Hello {text}" words = text.split(",")

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
str.split()Method文字列を部分文字列のリストに分割します。
str.join()Methodイテラブルの要素を指定した区切り文字で連結します。

そのまま実行できるコード例

Compilra で実行可能

Python をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

# String Formatting and Common Methods
raw_input = "   [email protected], [email protected]   "

# Clean whitespace and split by delimiter
cleaned = raw_input.strip()
emails = [e.strip() for e in cleaned.split(",")]
print(f"Parsed Emails: {emails}")

# String search & replacement
domain_target = "compilra.dev"
for email in emails:
    if email.endswith(domain_target):
        prefix = email.split("@")[0]
        print(f"Verified internal user: {prefix.upper()}")

# Joining elements
joined_names = " | ".join(["Python", "JavaScript", "C++"])
print(f"Joined: {joined_names}")
期待される出力:
Parsed Emails: ['[email protected]', '[email protected]']
Verified internal user: ADMIN
Verified internal user: DEVELOPER
Joined: Python | JavaScript | C++

動作のしくみ: ステップ解説

  • 5-6 行目: strip() で前後の空白を除去し、split(",") でトークンを分割します。
  • 11-14 行目: endswith() で接尾辞を確認し、.upper() で大文字に変換します。
  • 17 行目: join() がカスタム区切り文字列でリスト要素を連結します。

重要ポイント

  • Python の文字列はイミュータブルであるため、メソッドは元の文字列を変更せず新しい文字列を返します。
  • str.strip() は先頭と末尾の空白文字を取り除きます。
  • str.split(sep) は区切り文字に基づいて文字列をリスト要素へ分割します。

よくある間違い: 文字列メソッドが元の文字列を直接変更すると思い込む

文字列は不変なので、メソッドは新しい文字列を返します。結果を再代入する必要があります。

❌ 誤り
name = "  alex  "
name.strip() # Does NOT change name
✅ 正しい例
name = "  alex  "
name = name.strip() # Correctly reassigns "alex"

関連するPythonチュートリアルとコンパイラ

Compilra で Python を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。