logo

Python – Nahradí všechny výskyty podřetězce v řetězci

Někdy při práci s řetězci Pythonu můžeme mít problém, kdy potřebujeme nahradit všechny výskyty podřetězce jinými.

Vstup : test_str = geeksforgeeks s1 = geeks s2 = abcd
Výstup : test_str = abcdforabcd Vysvětlení: Všechny výskyty s1 nahradíme s2 v test_str.



náhodný c

Vstup : test_str = geeksforgeeks s1 = pro s2 = abcd
Výstup : test_str = geeksabcdgeeks

Přístup 1

Můžeme použít vestavěnou funkci nahradit přítomnou v pythonu3 k nahrazení všech výskytů podřetězce.



Implementace pomocí vestavěné funkce: -

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

>

>

Výstup

abcdforabcd>

Časová náročnost: Na)
Pomocný prostor: Na)

Přístup 2:

Používá se rozdělení řetězce podřetězcem a následné nahrazení novou funkcí 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>

>

>

Výstup

abcdforabcd>

Časová a prostorová složitost pro všechny metody je stejná:

Časová náročnost: Na)

Pomocný prostor: Na)

Metoda 3: Dalším způsobem, jak nahradit všechny výskyty podřetězce v řetězci, je použití re.sub() funkce z modulu re v pythonu.

Python3


kolik je 10 z 60



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

>

>

Výstup

abcdforabcd>

Časová náročnost: O(n), kde n je délka vstupního řetězce. Je to proto, že funkce re.sub() prochází celým vstupním řetězcem a provádí shodu regulárního výrazu na každém znaku, aby nalezla všechny výskyty podřetězce. Počet iterací je přímo úměrný délce vstupního řetězce.
Pomocný prostor: Nový

Metoda 4: Použití jednoduché iterace

Myšlenkou tohoto přístupu je procházet vstupní řetězec znak po znaku a kontrolovat, zda každý podřetězec délky m odpovídá podřetězci, který chceme nahradit. Pokud ano, přidáme náhradní podřetězec k našemu výsledku a posuneme ukazatel dopředu o m znaků. Pokud se neshoduje, přidáme k výsledku aktuální znak a posuneme ukazatel dopředu 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))>

>

>

Výstup

abcdforabcd>

Časová složitost: O(nm), kde n je délka vstupního řetězce a m je délka podřetězce, který má být nahrazen.
Pomocný prostor: O(n), protože vytváříme nový řetězec pro uložení výsledku.