Python – Zamień wszystkie wystąpienia podciągu w ciągu

Czasami podczas pracy z ciągami znaków w Pythonie możemy napotkać problem polegający na konieczności zastąpienia wszystkich wystąpień danego podciągu innym.

Wejście : test_str = geeksforgeeks s1 = maniak s2 = abcd
Wyjście : test_str = abcdforabcd Objaśnienie: Zamieniamy wszystkie wystąpienia s1 na s2 w test_str.

Wejście : test_str = geeksforgeeks s1 = dla s2 = abcd
Wyjście : test_str = geeksabcdgeeks

Podejście 1

Możemy użyć wbudowanej funkcji zamiany obecnej w Pythonie3, aby zastąpić wszystkie wystąpienia podciągu.

Implementacja przy użyciu wbudowanej funkcji: -

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

Wyjście

abcdforabcd 

Złożoność czasowa: NA)
Przestrzeń pomocnicza: NA)

Podejście 2:

Stosowane jest dzielenie ciągu przez podciąg, a następnie zastępowanie go nową funkcją 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>

Wyjście

abcdforabcd 

Złożoność czasowo-przestrzenna dla wszystkich metod jest taka sama:

Złożoność czasowa: NA)

Przestrzeń pomocnicza: NA)

Metoda 3: Innym podejściem do zastąpienia wszystkich wystąpień podciągu w ciągu jest użycie metody re.sub() funkcja z modułu re w Pythonie.

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

Wyjście

abcdforabcd 

Złożoność czasowa: O(n), gdzie n jest długością ciągu wejściowego. Dzieje się tak, ponieważ funkcja re.sub() iteruje po całym łańcuchu wejściowym i wykonuje dopasowanie wyrażenia regularnego na każdym znaku, aby znaleźć wszystkie wystąpienia podciągu. Liczba iteracji jest wprost proporcjonalna do długości ciągu wejściowego.
Przestrzeń pomocnicza: nowa

Metoda 4: Użycie prostej iteracji

Ideą tego podejścia jest iteracja po ciągu wejściowym znak po znaku i sprawdzanie, czy każdy podciąg o długości m pasuje do podciągu, który chcemy zastąpić. Jeśli tak, dodajemy podciąg zastępczy do naszego wyniku i przesuwamy wskaźnik do przodu o m znaków. Jeśli nie pasuje, dodajemy bieżący znak do wyniku i przesuwamy wskaźnik do przodu o 1 znak.

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

Wyjście

abcdforabcd 

Złożoność czasowa: O(nm), gdzie n jest długością ciągu wejściowego, a m jest długością podciągu, który ma zostać zastąpiony.
Przestrzeń pomocnicza: O(n), ponieważ tworzymy nowy ciąg do przechowywania wyniku.