logo

Python: sostituisce tutte le occorrenze di una sottostringa in una stringa

A volte, mentre lavoriamo con le stringhe Python, possiamo avere un problema in cui dobbiamo sostituire tutte le occorrenze di una sottostringa con altre.

Ingresso: test_str = geeksforgeeks s1 = geeks s2 = abcd
Produzione : test_str = abcdforabcd Spiegazione: Sostituiamo tutte le occorrenze di s1 con s2 in test_str.



Ingresso: test_str = geeksforgeeks s1 = for s2 = abcd
Produzione : test_str = geeksabcdgeeks

Approccio 1

Possiamo usare la funzione incorporata replace presente in python3 per sostituire tutte le occorrenze della sottostringa.



Implementazione utilizzando la funzione integrata: -

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)>

>

>

Produzione

abcdforabcd>

Complessità temporale: SU)
Spazio ausiliario: SU)

Approccio 2:

Viene utilizzata la divisione della stringa per sottostringa e quindi la sostituzione con la nuova funzione 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>

>

>

Produzione

abcdforabcd>

La complessità temporale e spaziale per tutti i metodi è la stessa:

Complessità temporale: SU)

Spazio ausiliario: SU)

Metodo 3: Un altro approccio per sostituire tutte le occorrenze di una sottostringa in una stringa consiste nell'utilizzare il metodo re.sub() funzione dal modulo re in Python.

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))>

imposta in Java

>

>

Produzione

abcdforabcd>

Complessità temporale: O(n), dove n è la lunghezza della stringa di input. Questo perché la funzione re.sub() scorre l'intera stringa di input ed esegue una corrispondenza con l'espressione regolare su ciascun carattere per trovare tutte le occorrenze della sottostringa. Il numero di iterazioni è direttamente proporzionale alla lunghezza della stringa di input.
Spazio ausiliario:Nuovo

Metodo 4: utilizzo dell'iterazione semplice

L'idea alla base di questo approccio è di scorrere la stringa di input carattere per carattere e verificare se ciascuna sottostringa di lunghezza m corrisponde alla sottostringa che vogliamo sostituire. In tal caso, aggiungiamo la sottostringa sostitutiva al nostro risultato e spostiamo il puntatore in avanti di m caratteri. Se non corrisponde, aggiungiamo il carattere corrente al risultato e spostiamo il puntatore in avanti di 1 carattere.

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))>

>

>

Produzione

abcdforabcd>

Complessità temporale: O(nm), dove n è la lunghezza della stringa di input e m è la lunghezza della sottostringa da sostituire.
Spazio ausiliario: O(n), poiché stiamo creando una nuova stringa per memorizzare il risultato.