So how do you get a sub-string in Python? Well, Python has a handy dandy feature called "slicing" that can be used for getting sub-strings from strings.

But first, we have to go over a couple of things to understand how this works.

Slicing Python Objects

Strings, in Python, are arrays of characters, except they act a little bit different than arrays. However, you can treat them, for the most part, as arrays.

Using this information, we can use Python's array functionality, called "slicing", on our strings! Slicing is a general piece of functionality that can be applied to any array-type object in Python.

Okay, so here's a concrete example using a simple array to start off.

As you can see, this gives us a subset of the array up to the 3rd element. Slicing takes in two "arguments" that specify the start and end position you would like in your array.

Syntax: array[start:end]

So in our example above, if we only wanted the elements 2 and 3, we would do the following:

Alright, alright. What does this have to do with sub-strings? Excellent question!

Getting Sub-strings: Slicing Python Strings!

Above, I mentioned that we can pretty much treat strings like arrays. That means that we can apply the same logic to our strings!

Here's an example:

Wow! We accessed the character just like it was an element in an array! Awesome!

So what we see here is a "sub-string". To get a sub-string from a string, it's as simple as inputting the desired start position of the string as well as the desired end position.

Of course, we can also omit either the start position, or the end position which will tell Python that we would like to either start our sub-string from the start, or end it at the end, respectively.

Here's another example using our string above.

Alright, that's all well and good, but what the heck did I do in that last line? I didn't specify the start or the end, so how come it still worked?

Well, what we did there was tell Python to get the start element all the way to the end element. It's completely valid. It also creates a new copy of the string or array. You could use this if you need a copy of the original to modify!

Reverse Sub-string Slicing in Python

Another example, using extended slicing, can get the sub-string in reverse order. This is just a "for fun" example, but if you ever need to reverse a string in Python, or get the reversed sub-string of a string, this could definitely help.

Here we go:

Awesome!

It's out of the scope of this article to explain extended slicing, so I won't say too much about it. The only thing different is that extra colon at the end and the number after it. The extra colon tells Python that this is an extended slice, and the "-1" is the index to use when traversing the string. If we had put a "1" where the "-1" is, we'd get the same result as before.

There you have it! It's really easy to get sub-strings in Python, and I hope I educated you more in Python-fu.

Hasta luego!

About The Author