Python – 文字列内の部分文字列をすべて置換します
Python 文字列を操作しているときに、出現するすべての部分文字列を別の文字列に置き換える必要があるという問題が発生することがあります。
入力: test_str = geeksforgeeks s1 = オタク s2 = abcd
出力: test_str = abcdforabcd 説明: test_str 内のすべての s1 を s2 に置き換えます。入力: test_str = geeksforgeeks s1 = s2 = abcd 用
出力: test_str = geeksabcdgeeks
アプローチ 1
Python3 に存在する組み込み関数 replace を使用して、出現するすべての部分文字列を置き換えることができます。
組み込み関数を使用した実装:-
Python3
#Python has inbuilt function replace to replace all occurrences of substring.> input_string> => 'geeksforgeeks'> s1> => 'geeks'> s2> => 'abcd'> input_string> => input_string.replace(s1, s2)> print> (input_string)> |
出力
abcdforabcd
時間計算量: の上)
補助スペース: の上)
アプローチ 2:
文字列を部分文字列で分割し、新しい string.split() 関数に置き換えます。
Python3
#code for replacing all occurrences of substring s1 with new string s2> test_str> => 'geeksforgeeks'> s1> => 'geeks'> s2> => 'abcd'> #string split by substring> s> => test_str.split(s1)> new_str> => ''> for> i> in> s:> > if> (i> => => ''):> > new_str> +> => s2> > else> :> > new_str> +> => i> #printing the replaced string> print> (new_str)> #contributed by Bhavya Koganti> |
出力
abcdforabcd
すべてのメソッドの時間と空間の複雑さは同じです。
時間計算量: の上)
補助スペース: の上)
方法 3: 文字列内のすべての部分文字列を置換する別の方法は、 re.sub() Pythonのreモジュールからの関数。
Python3
import> re> def> replace_substring(test_str, s1, s2):> > # Replacing all occurrences of substring s1 with s2> > test_str> => re.sub(s1, s2, test_str)> > return> test_str> # test> test_str> => 'geeksforgeeks'> s1> => 'geeks'> s2> => 'abcd'> print> (replace_substring(test_str, s1, s2))> |
出力
abcdforabcd
時間計算量: O(n)。n は入力文字列の長さです。これは、 re.sub() 関数が入力文字列全体を反復処理し、各文字に対して正規表現の一致を実行して、出現する部分文字列をすべて検索するためです。反復回数は入力文字列の長さに正比例します。
補助スペース:新規
方法 4: 単純な反復を使用する
このアプローチの背後にある考え方は、入力文字列を 1 文字ずつ反復処理し、長さ m の各部分文字列が置換する部分文字列と一致するかどうかを確認することです。存在する場合は、置換部分文字列を結果に追加し、ポインタを m 文字分前方に移動します。一致しない場合は、現在の文字を結果に追加し、ポインタを 1 文字分進めます。
Python3
def> replace_substring(test_str, s1, s2):> > # Initialize an empty string to store the result> > result> => ''> > # Initialize a variable to keep track of our position in the string> > i> => 0> > # Loop through the string one character at a time> > while> i <> len> (test_str):> > # Check if the current substring matches the substring we want to replace> > if> test_str[i:i> +> len> (s1)]> => => s1:> > # If it does, add the replacement substring to the result and move the pointer forward> > result> +> => s2> > i> +> => len> (s1)> > else> :> > # If it doesn't, add the current character to the result and move the pointer forward> > result> +> => test_str[i]> > i> +> => 1> > # Return the final result> > return> result> # test> test_str> => 'geeksforgeeks'> s1> => 'geeks'> s2> => 'abcd'> print> (replace_substring(test_str, s1, s2))> |
出力
abcdforabcd
時間計算量: O(nm)。n は入力文字列の長さ、m は置換される部分文字列の長さです。
補助スペース: O(n)。結果を保存するための新しい文字列を作成しているためです。