Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

String Slicing (Solution)

00:00 My task is to slice bazinga to get zing. So I’ll start off by assigning the string "bazinga" to a variable. So I’m just going to call it word in that case. Is bazinga a real word? Okay, here we have "bazinga", and then I’m going to use slice notation to get out the zinga part of it.

00:25 And to use slice notation, you use square brackets,

00:29 and inside of the square brackets, you have to put in the indexes that you want to use. String indexing starts with zero, so b is at the index zero, a is the index one, and then we have z at the index two.

00:45 So I can start off with two. And then in this case, I want to get everything that starts at two and goes to the end. So I can just do that by putting a colon there.

00:56 So by typing word[2:] I should get out just the string zinga. And let’s confirm by pressing Enter. Here it is, I sliced out zinga from bazinga,

01:10 but when I look at the task again, I actually shouldn’t get zinga, but I should get the word zing. So there’s a little more that I need to do here.

01:20 So instead of going all the way to the end, which I did here by just putting the colon and then not specifying a stopping index, I’ll have to specify the stop index as well.

01:31 And that could be by saying word and again starting at two and then going up to—so this was two, then the i is three, and n is four, and the g is five, and then the a is six, and you have to specify one plus the last character that you want to get.

01:51 So I want to go to six, which is the index of a, and that means that I’m going to get everything up to a. So word[2:6] should give me the actual string that I’m looking for, which is zing.

02:05 There you go. However, if you have a longer string, and you want to get everything up to maybe the final character but not the final character, then counting like this can get quite hard.

02:16 So instead, you can go backwards, and you can also count indices starting with a minus. So the first one is going to be minus one, and then g is going to be minus two, et cetera.

02:27 So I can instead specify word starting from two and then going all the way up to minus one,

02:36 which is going to do the same as saying two up to six. In this case, it’s going to go from here up to, but not including, the final character. So that’s another way to just get zing. All right.

02:50 And that’s actually the task, getting zing. And now I’ve found two ways to get zing without the final character, a.

Become a Member to join the conversation.