Alvaro Joao Alvaro Joao - 1 year ago 112
Python Question

Python best way to remove char from string by index

I'm removing an char from string like this:

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

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download