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.
Answer from Mad Physicist on Stack OverflowYou 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.
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.
Remove char at specific index - python - Stack Overflow
Remove substring via index
how to remove a character from a string in 3.11.4?
python - Remove multiple indices of a string - Stack Overflow
To remove the substring from index i to j in some string s, I know I can use string slicing:
s = s[:i] + s[j+1:]
I also know to delete a single character I can replace that character with โโ or convert to a bytestring:
del bytearray(s)[i]
s.replace(โcโ, โโ, 1)
Are there any other fundamental ways to delete a substring via index? I prefer the bytestring way as itโs most direct.
Thank you
Strings are immutable. So deleting elements from it will not work.
data = "Welcome"
del data[0]
# TypeError: 'str' object doesn't support item deletion
The best way is to reconstruct the string without the elements from the specific indexes and join them together, like this
data, indexes = "Welcome", {1, 3, 5}
print "".join([char for idx, char in enumerate(data) if idx not in indexes])
# Wloe
Note that the indexes is a set of numbers, since sets offer faster lookup than the lists. If you have a list of numbers like [1, 3, 5] and if you want to convert them to a set, use set function to do that, like this set([1, 3, 5])
You can use the builtin bytearray for this
def delete(string, indices):
z = bytearray(string.encode())
for i in sorted(indices, key=abs, reverse=True):
del z[i]
return z.decode()
delete('Hello world!', [0, -3])
'ello word!'
Beware that this will only work for ascii character strings where the str -> byte mapping is one-to-one.