str.partition() sep で 3 つに分割
最終更新:2026-09-22
str.partition() sep で 3 つに分割
str.partition(sep) (before, sep, after) のタプルを返す。sep が見つからない場合は (元の文字列, '', '') を返す。
| カテゴリ | 文字列メソッド |
|---|---|
| 種類 | 組み込み型メソッド |
| Python バージョン | all |
📝 構文
str.partition(sep)
⚙️ 引数
| sep 必須 | The separator substring to split at. |
|---|
戻り値:tuple. (head, sep, tail); if sep is absent, returns (string, '', '').
元のオブジェクトを変更するか:いいえ(新しいオブジェクトを返す)
💥 例外
ValueError— Raised when sep is an empty string.
▶ 例
下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:
実行結果:
('a', '=', 'b=c')
('hello', '', '')
💡 関連するケース
さらに多くのケースは近日公開予定です。
❓ よくある質問
Q区切り文字が見つからないときは何を返しますか?
Aエラーを発生させずに (original_string, '', '') を返します。
Qこれは何型を返しますか?
A常に 3 要素タプル (before, sep, after) を返します。'a=b=c'.partition('=') は ('a', '=', 'b=c') を返し、最初の出現位置でのみ分割します。
Qsep が空文字列の場合はどうなりますか?
AValueError: empty separator が発生します。
Qsplit() との違いは何ですか?
Apartition() は 1 回だけ分割し、3 要素タプルを返し、区切り文字を保持します。split() は複数回分割し、リストを返し、区切り文字を捨てます。