logo

Come rimuovere le lettere da una stringa in Python

Le stringhe sono tipi di dati utilizzati per rappresentare testo/caratteri. In questo articolo presentiamo diversi metodi per risolvere il problema della rimozione dell'ithcarattere da una stringa e parlare delle possibili soluzioni che possono essere impiegate per realizzarli utilizzando Python.

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

Rimuovi caratteri da una stringa in Python

Questi sono i seguenti metodi con cui possiamo rimuovere lettere da una stringa in Pitone :

  • Utilizzando str.sostituisci()
  • Utilizzando tradurre()
  • Utilizzando ricorsione
  • Utilizzando il metodo nativo
  • Utilizzando slice + concatenazione
  • Utilizzando str.join()
  • Utilizzando bytearray
  • Utilizzando rimuoviprefisso ()

Rimuovere i caratteri da una stringa utilizzando replace()

str.sostituisci() può essere utilizzato per sostituire tutte le occorrenze del carattere desiderato. Può anche essere utilizzato per eseguire l'attività di rimozione dei caratteri da una stringa poiché possiamo sostituire l'indice particolare con un carattere vuoto e quindi risolvere il problema.



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

>

altrimenti se bash
>

Produzione

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

Complessità temporale: SU)
Complessità spaziale: SU)

Inconveniente: Lo svantaggio principale dell'utilizzo di replace() è che fallisce nei casi in cui sono presenti duplicati in una stringa che corrisponde al carattere in pos. io. replace() sostituisce tutte le occorrenze di un particolare carattere e quindi sostituirebbe tutte le occorrenze di tutti i caratteri in pos i. Talvolta possiamo ancora utilizzare questa funzione se il carattere sostitutivo corrisponde a 1sttempo nella stringa.

Rimuovi il carattere specifico dalla stringa usando Translate()

Questo metodo fornisce un meccanismo efficace per rimuovere caratteri da una stringa. In questo metodo, abbiamo rimosso 123 da techcodeview.com utilizzando stringa.translate() .

Python3




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

>

>

Produzione

GeeksForGeeks>

Complessità temporale: SU)
Complessità spaziale: O(m)

Rimuovere il carattere specifico dalla stringa utilizzando la ricorsione

Per rimuovere il carattere i-esimo da una stringa utilizzando la ricorsione, è possibile definire una funzione ricorsiva che accetta la stringa e l'indice da rimuovere come argomenti. La funzione controllerà se l'indice è uguale a 0, in questo caso restituisce la stringa con il primo carattere rimosso. Se l'indice è diverso da 0, la funzione può restituire il primo carattere della stringa concatenato con il risultato di richiamare nuovamente la funzione sulla stringa con l'indice decrementato di 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>

>

>

Produzione

The string after removal of ith character: GeksForGeeks>

Complessità temporale: SU)
Complessità spaziale: SU)

Rimuovere le lettere da una stringa utilizzando il metodo nativo

In questo metodo, è sufficiente eseguire a Ciclo di Python e aggiungi i caratteri man mano che vengono e crea una nuova stringa da quella esistente tranne quando l'indice è 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)>

>

>

Produzione

The string after removal of i'th character : GeksForGeeks>

Complessità temporale: SU)
Complessità spaziale: O(n), dove n è la lunghezza della stringa.

Rimuovi l'ithCarattere della stringa che utilizza Slice

Si può usare fetta di corda e taglia la corda prima della pos i e taglia dopo la pos i. Quindi utilizzando concatenazione di stringhe di entrambi, ithpuò sembrare che il carattere sia stato eliminato dalla stringa.

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

Codici di errore di Linux

>

>

Produzione

The string after removal of i'th character : GeksForGeeks>

Complessità temporale: SU)
Complessità spaziale: SU)

Rimuovi l'ithCarattere dalla stringa Using str.join()

In questo metodo, ogni elemento di una stringa viene prima convertito come ogni elemento dell'elenco, quindi ciascuno di essi viene unito per formare una stringa tranne l'indice specificato.

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

>

>

Produzione

The string after removal of i'th character : GeksForGeeks>

Complessità temporale: SU)
Complessità spaziale: SU)

Elimina lettere da una stringa in Python usando bytearray

Definire la funzione Remove_char(s, i) che accetta una stringa s e un intero i come input. E poi converti la stringa di input s in un bytearray usando bytearray(s, 'utf-8'). Elimina l'i-esimo elemento da bytearray utilizzando del b[i]. Converti nuovamente il bytearray modificato in una stringa utilizzando b.decode() e restituisci la stringa modificata.

Python3

architettura linux




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

>

>

Produzione

hell world>

Complessità temporale: SU)
Complessità spaziale: SU)

Rimuovi lettere da una stringa usando rimuoviprefisso()

rimuoviprefisso() rimuove il prefisso e restituisce il resto della stringa. Possiamo rimuovere lettere da una stringa per qualsiasi indice specifico dividendo la stringa in due metà in modo tale che la lettera che vogliamo rimuovere si trovi nel prefisso di una qualsiasi delle due partizioni e quindi possiamo applicare il metodo per rimuovere la lettera.

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

>

>

Produzione:

eeksforGeeks GeeksorGeeks>

Complessità temporale: SU)
Complessità spaziale: SU)