Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python best way to remove char from string by index

Tags:

I'm removing an char from string like this:

S = "abcd" Index=1 #index of string to remove ListS = list(S) ListS.pop(Index) S = "".join(ListS) print S #"acd" 

I'm sure that this is not the best way to do it.

EDIT I didn't mentioned that I need to manipulate a string size with length ~ 10^7. So it's important to care about efficiency.

Can someone help me. Which pythonic way to do it?

like image 428
Alvaro Joao Avatar asked Jun 28 '16 04:06

Alvaro Joao


People also ask

How do I remove a character from a string in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

How do you get rid of a certain character in a string?

You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement.


1 Answers

You can bypass all the list operations with slicing:

S = S[:1] + S[2:] 

or more generally

S = S[:Index] + S[Index + 1:] 

Many answers to your question (including ones like this) can be found here: How to delete a character from a string using python?. However, that question is nominally about deleting by value, not by index.

like image 100
Mad Physicist Avatar answered Oct 03 '22 14:10

Mad Physicist