Can we only slice strings as a sequence of adjacent characters?

Question

In Python, is slicing strings limited to a sequence of characters adjacent to each other? Can we skip characters?

Answer

String slicing is not only limited to a sequence of adjacent characters, and you can skip character when slicing.

String slicing can utilize an optional third argument to specify a ‘step’ or ‘stride’ between each character as the substring is being constructed. By default, the step is 1. By changing the step, we can do some interesting things.

Example

message = "MXeXeXtX XmXeX XaXtX XtXhXeX XpXaXrXkX"

decoded = message[0:38:2]

print(decoded)
# Meet me at the park
11 Likes

Even the spaces are taking indices in strings? right?

6 Likes

A blankspace is a character and each blankspace does indeed take up one position in the string, with a corresponding index.

17 Likes

Per the exercise Create a variable new_account by slicing the first five letters of his last_name. if the index starts at 0, why would it not be last_name[:4]

I believe when using string[a:b], the beginning is inclusive but the end is not. So in this case, to have the 5th letter included, you have to do input 5 instead of 4. Similar to the range function below, the result would not include 5 but only 4.
print(list(range(5)))

[0, 1, 2, 3, 4]

2 Likes

I copied the image Codecademy used to explain it.

hope that helps!

If you want to include the last letter, you could use the [-1] index instead of the last number. Following the example from this thread, it would be like this:

message = "MXeXeXtX XmXeX XaXtX XtXhXeX XpXaXrXkX"

decoded = message[0:-1:2]

print(decoded)
# Meet me at the park

Using -1 you make sure to include the last character from your string.

2 Likes