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?

2
  • Your example does not seem to demonstrate obtaining what's left after a slice. Commented Mar 12, 2015 at 19:44
  • @wwii The assumed slice you're removing is myString[4:-5]. Commented Mar 12, 2015 at 19:45

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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: 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.
@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).
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?

4 Comments

Nice workaround. When working with future data that could be unknown, it wouldn't be safe to assume that it will be unique unfortunately.
@horta, yep it is limited but about as close as you will get to a single step
Note this is still two separate steps, it's just a different two steps than in the example in the question.
@BrenBarn, yes and it is limited but about as close as the OP is going to get to what they want to do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.