cSn
cSn

Reputation: 2906

String slices/substrings/ranges in Python

I'm newbie in Python and I would like to know something that I found very curious.

Let's say I have this:

s = "hello"

Then:

s[1:4] prints "ell" which makes sense... and then s[3:-1] prints 'l' only that does makes sense too..

But!

s[-1:3] which is same range but backwards returns an empty string ''... and s[1:10] or s[1:-20] is not throwing an error at all.. which.. from my point of view, it should produce an error right? A typical out-of-bounds error.. :S

My conclusion is that the range are always from left to right, I would like to confirm with the community if this is as I'm saying or not.

Thanks!

Upvotes: 3

Views: 95

Answers (2)

6502
6502

Reputation: 114481

Ranges are "clamped" to the extent of the string... i.e.

s[:10]

will return the first 10 characters, or less if the string is not long enough.

A negative index means starting counting from the end, so s[-3:] takes the last three characters (or less if the string is shorter).

You can have range backward but you need to use an explicit step, like

s[10:5:-1]

You can also simply get the reverse of a string with

s[::-1]

or the string composed by taking all chars in even position with

s[::2]

Upvotes: 3

jgritty
jgritty

Reputation: 11915

s[-1:3] returns the empty string because there is nothing in that range. It is requesting the range from the last character, to the third character, moving to the right, but the last character is already past the third character.

Ranges are by default left to right.

There are extended slices which can reverse the step, or change it's size. So s[-1:3:-1] will give you just 'o'. The last -1 in that slice is telling you that the slice should move from right to left.

Slices won't throw errors if you request a range that isn't in the string, they just return an empty string for those positions.

Upvotes: 3

Related Questions