pythonで文字列を置換する方法/replaceメソッドの使い方

room IT

replaceメソッドを使うと、文字列を他の文字列に置換(置き換え)することができます。

スポンサーリンク

replaceメソッド

python replace1
テスト用にprint関数で通常の文字列を打ち出すコードを用意しました。
python replace2
replaceメソッドは、対象となる文字列の後ろに.replaceをつけ、
#python
print("abc".replace("a","A"))
引数に元の文字列、置き換える文字列をそれぞれ指定します。
この場合aAに置換しようとしています。
python replace3
実行結果です。
python replace4
元の文字列が空欄の場合、図のように文字の前後にそれぞれ置き換える文字列が接着します。
※スペースの前後には接着しません。
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。 初期準備、基本概念 ダウンロード、インストール、起動 ShellとEditor、保存、実行 保存したPythonの起動 コメント、docstring、行またぎ コメント、...

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny