How could I remove all items in between 2 indexes in a list/tuple?
e.g 'abcdefghijklmnop'
with begin = 4
and end = 7
should result in 'abcdhijklmnop'
('efg'
removed)
Asked
Active
Viewed 75 times
0

AvidProgrammer
- 103
- 2
- 8
-
do `begin` and `end` refer to indices or the actual characters in the string? – Vedank Pande Apr 03 '21 at 10:06
-
They refer to indices – AvidProgrammer Apr 03 '21 at 10:06
-
Does this answer your question? [Python best way to remove char from string by index](https://stackoverflow.com/questions/38066836/python-best-way-to-remove-char-from-string-by-index) – mkrieger1 Apr 03 '21 at 10:12
3 Answers
1
You can use list slicing:
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = a[:3] + a[7:]
print(b)
The result is [1, 2, 3, 8]

NirO
- 216
- 2
- 12
1
Try this:
ip = '123456789'
begin = 3
end = 6
res = ip[:begin]+ip[end:]
output:
123789

Vedank Pande
- 436
- 3
- 10
1
You can use list slicing as below:
li = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']
del li[4:7]
print(li)
output:
['a', 'b', 'c', 'd', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
As in the post, you've provided it as a string, so in that case you can use string slicing:
s= 'abcdefghijklmnop'
start = 4
end = 7
s= s[0: start:] + s[end::]
print(s)
output:
abcdhijklmnop

User123
- 1,498
- 2
- 12
- 26