Posts

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 re