Python String Slicing

A string is simply a sequence of characters, either a word or a sentence.
They are surrounded by either a single or double quotes. It is easy to see string in python a single value, just like a typical integer. Below is a string variable:

# declaring a string variable
firstName = "Folorunso"


But string is actually a group of individually indexed characters. And just like in many other programming languages, python is also zero based indexed; meaning the first item/character in any python collection/sequence will be at index 0. This means that the 'F' character in the firstName variable above is at index 0 and 's' is at index 7.

Extracting substring

We use square brackets to return portions/parts of a string as required.

# returning substrings

>>> firstName[0] # returns 'F'
>>> firstName[7] # returns 's'
>>> firstName[0:4] # returns 'Folo' .. when you do a range of characters like this, you read like this: extract from index 0 to index 4 exclusive. Exclusive means do not include the character at index 4.

>>> firstName[-1] # returns 'o'... indexing can also be read backwardly. -1 will return the last character in the string.


There are other interesting things you can do with strings in python. I will be blogging on these from time to time. For a classroom or one-on-one in-depth python development training, you can enroll for a python course on Anchorsoft website.

Comments