0

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)

AvidProgrammer
  • 103
  • 2
  • 8

3 Answers3

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