2

This substring related question appears to never mention another potential goal when slicing strings: obtaining what's left after a slice.

Is there a way to get what's left over when performing a slice operation without two separate steps where you join what's left over?

This would be brute force way, but it uses two slice operations and a join.

myString = "how now brown trow?"  
myString[:4] + myString[-5:]  
>>> 'how trow?'

Can this be done using the slicing notation without making two slices and joining them together?

Community
  • 1
  • 1
horta
  • 1,110
  • 8
  • 17

2 Answers2

2

No. You can't get non-contiguous pieces with a single slice operation.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • I was hoping since the index was contiguous forward and backwards, that the slice would still be classified as contiguous through the wrap-around. – horta Mar 12 '15 at 19:48
  • @horta: No, you can't get slices that are only contiguous through wraparound. You can slice forward or backward, but not both in the same slice. – BrenBarn Mar 12 '15 at 19:49
  • @horta This is also not just pure rotation of the string, because you actually want "how trow?", and not "trow?how", which is what you would get from reading it with wrap around (which can be accomplished with a comprehension). – Asad Saeeduddin Mar 12 '15 at 19:56
2

If the slice is unique that you want to remove you could str.replace:

myString = "how now brown trow?"
s = myString.replace(myString[4:-5],"")
print(s)
how trow?
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321