Python best way to remove char from string by index

S = "abcd"
Index=1 #index of string to remove
S = S.replace(S[Index], "")
print(S)

I hope it helps!


Slicing is the best and easiest approach I can think of, here are some other alternatives:

>>> s = 'abcd'
>>> def remove(s, indx):
        return ''.join(x for x in s if s.index(x) != indx)

>>> remove(s, 1)
'acd'
>>> 
>>> 
>>> def remove(s, indx):
        return ''.join(filter(lambda x: s.index(x) != 1, s))

>>> remove(s, 1)
'acd'

Remember that indexing is zero-based.


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.


You can replace the Index character with "".

str = "ab1cd1ef"
Index = 3
print(str.replace(str[Index],"",1))