Slicing Strings

You have seen how you can use index numbers in Python to get at single characters in a string of text:

myText = "String"
print( myText[2] )

But you can also use index numbers to get at more than one character in your text. This is called slicing.

To grab more than one character from a string of text, you use two values separated by a colon ( : ). Here's an example for you to try:

myText = "String"
mySlice = myText[0:2]
print( mySlice )

In your output window, you should see the letters St appear.

The first number, the one before the colon is the starting position. The count starts at zero. This points to just before the first letter. The 2 points to a position just after the second letter. Python then grabs characters from your first number up to your second number. Here's an image that might help you understand the concept:

A Python string's index numbers

This slice, then:

myText[2: 4]

would grab the characters ri. The 2 starts just before the letter r. The four starts just after the letter i. Python grabs from just before the 2 to before the 4.

Try it out. Change the 0:2 from the code you have to 2:4.

If you want to grab characters from the start of a string, you can miss out the zero, if you want. Just do this:

myText[: 2]

This is a shorthand way of saying:

myText[0: 2]

Quite often, you'll want to grab characters to the end of your string. In which case, you can miss out the second number:

myText = "String"
mySlice = myText[2:]

The code above prints the letters ring. It starts at the 2 and then grabs characters right to the end of the string.

Slicing is well worth getting the hang of because you never know when it will come in handy. Try these slicing exercises.

Python Exercise

Suppose you had a person's name in a variable:

myName = "Kenny Carney"

However, you want the surname Carney first and then the first name of Kenny. Use slicing to print out Carney Kenny.

Remember: you can use the plus symbol and spaces to concatenate:

print(surname + " " + firstName)

Python Exercise

Set up a new variable with the value "Kenny Carney". Now use slicing to swap the first two letters of the surname with the first two letters of the first name. Replace the first two letters of the first name with the first two letters of the surname. So you want to go from this:

myName = "Kenny Carney"

to this:

myName = "Canny Kerney"

This exercise is a lot trickier than the previous one. You can do it in four slices, though. Grab the first two letters of Kenny, then a second slice to grab the first two characters of Carney. Then use a third slice to get the nny and a fourth slice to get rney. Once you have all four slices you can rearrange them.

In the next lesson, we'll have at replace in Python.

Python Replace >