Kako odstraniti črke iz niza v Pythonu

Nizi so tipi podatkov, ki se uporabljajo za predstavitev besedila/znakov. V tem članku predstavljamo različne metode za reševanje problema odstranjevanja i th znak iz niza in se pogovorite o možnih rešitvah, ki jih je mogoče uporabiti pri doseganju le-teh z uporabo Pythona.

  Input:   'Geeks123For123Geeks'   Output:   GeeksForGeeks   Explanation:   In This, we have removed the '123' character from a string. 

Odstranite znake iz niza v Pythonu

To so naslednje metode, s katerimi lahko odstranimo črke iz niza v Python :

Odstranite znake iz niza z uporabo replace()

str.replace() lahko uporabite za zamenjavo vseh pojavitev želenega znaka. Lahko se uporablja tudi za izvajanje naloge odstranjevanja znakov iz niza, saj lahko določen indeks nadomestimo s praznim znakom in s tem rešimo težavo.

Python3




# Initializing String> test_str> => 'GeeksForGeeks'> # Removing char at pos 3> # using replace> new_str> => test_str.replace(> 'e'> , '')> # Printing string after removal> # removes all occurrences of 'e'> print> (> 'The string after removal of i'th character( doesn't work) : '> +> new_str)> # Removing 1st occurrence of s, i.e 5th pos.> # if we wish to remove it.> new_str> => test_str.replace(> 's'> , '',> 1> )> # Printing string after removal> # removes first occurrences of s> print> (> 'The string after removal of i'th character(works) : '> +> new_str)>

Izhod

The string after removal of i'th character( doesn't work) : GksForGks The string after removal of i'th character(works) : GeekForGeeks 

Časovna zapletenost: O(n)
Kompleksnost prostora: O(n)

Slabost: Glavna pomanjkljivost uporabe replace() je, da ne uspe v primerih, ko so v nizu dvojniki, ki se ujemajo s char na pos. jaz. replace() zamenja vse pojavitve določenega znaka in bi tako zamenjal vse pojavitve vseh znakov na pos i. Še vedno lahko včasih uporabimo to funkcijo, če se nadomestni znak pojavi za 1 st čas v nizu.

Odstranite določen znak iz niza s funkcijo Translate()

Ta metoda zagotavlja močan mehanizem za odstranjevanje znakov iz niza. Pri tej metodi smo odstranili 123 iz techcodeview.com z uporabo string.translate() .

Python3




str> => 'Geeks123For123Geeks'> > print> (> str> .translate({> ord> (i):> None> for> i> in> '123'> }))>

Izhod

GeeksForGeeks 

Časovna zapletenost: O(n)
Kompleksnost prostora: O(m)

Odstranite določen znak iz niza z uporabo rekurzije

Če želite odstraniti znak i iz niza z uporabo rekurzije, lahko definirate rekurzivno funkcijo, ki vzame niz in indeks, ki ju je treba odstraniti, kot argumenta. Funkcija bo preverila, ali je indeks enak 0, v tem primeru vrne niz z odstranjenim prvim znakom. Če indeks ni 0, lahko funkcija vrne prvi znak niza, povezanega z rezultatom ponovnega klica funkcije v nizu z indeksom, zmanjšanim za 1.

Python3




def> remove_ith_character(s, i):> > # Base case: if index is 0,> > # return string with first character removed> > if> i> => => 0> :> > return> s[> 1> :]> > # Recursive case: return first character> > # concatenated with result of calling function> > # on string with index decremented by 1> > return> s[> 0> ]> +> remove_ith_character(s[> 1> :], i> -> 1> )> # Test the function> test_str> => 'GeeksForGeeks'> new_str> => remove_ith_character(test_str,> 2> )> print> (> 'The string after removal of ith character:'> , new_str)> # This code is contributed by Edula Vinay Kumar Reddy>

Izhod

The string after removal of ith character: GeksForGeeks 

Časovna zapletenost: O(n)
Kompleksnost prostora: O(n)

Odstranite črke iz niza z izvorno metodo

Pri tej metodi je treba samo zagnati a Pythonova zanka in dodajte znake, ko pridejo, ter zgradite nov niz iz obstoječega, razen če je indeks i.

Python3




test_str> => 'GeeksForGeeks'> # Removing char at pos 3> new_str> => ''> for> i> in> range> (> len> (test_str)):> > if> i !> => 2> :> > new_str> => new_str> +> test_str[i]> # Printing string after removal> print> (> 'The string after removal of i'th character : '> +> new_str)>

Izhod

The string after removal of i'th character : GeksForGeeks 

Časovna zapletenost: O(n)
Kompleksnost prostora: O(n), kjer je n dolžina niza.

Odstranite i th Znak iz niza, ki uporablja rezino

Eden lahko uporablja rezina vrvice in prerežite vrvico pred pos i in rezino za pos i. Nato z uporabo združevanje nizov od obeh, i th se lahko zdi, da je znak izbrisan iz niza.

Python3




# Initializing String> test_str> => 'GeeksForGeeks'> # Removing char at pos 3> # using slice + concatenation> new_str> => test_str[:> 2> ]> +> test_str[> 3> :]> # Printing string after removal> # removes ele. at 3rd index> print> (> 'The string after removal of i'th character : '> +> new_str)>

Izhod

The string after removal of i'th character : GeksForGeeks 

Časovna zapletenost: O(n)
Kompleksnost prostora: O(n)

Odstranite i th Uporaba znaka iz niza str.join()

Pri tej metodi se vsak element niza najprej pretvori kot vsak element seznama, nato pa se vsak od njih združi v niz, razen podanega indeksa.

Python3




# Initializing String> test_str> => 'GeeksForGeeks'> # Removing char at pos 3> # using join() + list comprehension> new_str> => ''.join([test_str[i]> for> i> in> range> (> len> (test_str))> if> i !> => 2> ])> # Printing string after removal> # removes ele. at 3rd index> print> (> 'The string after removal of i'th character : '> +> new_str)>

Izhod

The string after removal of i'th character : GeksForGeeks 

Časovna zapletenost: O(n)
Kompleksnost prostora: O(n)

Brisanje črk iz niza v Pythonu z uporabo bytearray

Definirajte funkcijo remove_char(s, i), ki kot vhod sprejme niz s in celo število i. In nato pretvorite vhodni niz s v niz bytearray z bytearray(s, 'utf-8'). Izbrišite i-ti element iz bytearray z uporabo del b[i]. Pretvorite spremenjeno niz bytearray nazaj v niz z uporabo b.decode() in vrnite spremenjeni niz.

Python3




def> remove_char(s, i):> > b> => bytearray(s,> 'utf-8'> )> > del> b[i]> > return> b.decode()> # Example usage> s> => 'hello world'> i> => 4> s> => remove_char(s, i)> print> (s)>

Izhod

hell world 

Časovna zapletenost: O(n)
Kompleksnost prostora: O(n)

Odstranite črke iz niza z uporabo removeprefix()

odstranipredpono() odstrani predpono in vrne preostali del niza. Črke lahko odstranimo iz niza za kateri koli določen indeks tako, da niz razdelimo na dve polovici, tako da je črka, ki smo jo želeli odstraniti, v predponi katere koli od obeh particij, nato pa lahko uporabimo metodo za odstranitev črke.

Python3




#initializing the string> s> => 'techcodeview.com'> #if you wanted to remove 'G' of 0th index> s1> => s.removeprefix(> 'G'> )> #if you wanted to remove 'f'> s2> => s[:> 5> ]> +> s[> 5> :].removeprefix(> 'f'> )> print> (s1)> print> (s2)>

Izhod:

eeksforGeeks GeeksorGeeks 

Časovna zapletenost: O(n)
Kompleksnost prostora: O(n)