Python-text-processing-python-word-replacement
提供:Dev Guides
Python-単語の置換
文字列全体または文字列の一部を置き換えることは、テキスト処理で非常に頻繁に必要になります。 * replace()*メソッドは、古いものが新しいものに置き換えられた文字列のコピーを返します。オプションで、置き換えの数を最大に制限します。
以下は* replace()*メソッドの構文です-
str.replace(old, new[, max])
パラメーター
- old -これは置き換えられる古い部分文字列です。
- new -これは新しい部分文字列で、古い部分文字列を置き換えます。
- max -このオプションの引数maxが指定された場合、最初のカウントのみが置換されます。
このメソッドは、部分文字列oldのすべての出現をnewに置き換えた文字列のコピーを返します。 オプションの引数maxが指定された場合、最初のカウントの出現のみが置き換えられます。
例
次の例は、replace()メソッドの使用法を示しています。
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
結果
上記のプログラムを実行すると、次の結果が生成されます-
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
交換無視ケース
import re
sourceline = re.compile("Tutor", re.IGNORECASE)
Replacedline = sourceline.sub("Tutor","finddevguides has the best tutorials for learning.")
print (Replacedline)
上記のプログラムを実行すると、次の出力が得られます-
finddevguides has the best Tutorials for learning.