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


#1

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