This Python substring tutorial covers retrieving substrings from strings. Remember that a substring is simply a part of a bigger string. Since Python treats strings as arrays, we can manipulate strings using array notation to retrieve substrings. This method is also called string slicing.
Getting substrings are useful when parsing data, for example to pull a certain number of characters from a string. Whatever your need for finding substrings is, the Python substring tutorial below will get you up to speed on using substrings in Python.
Let's dive right in with an example Python script. The comments in the code give an indication of what each instruction does.
#!/usr/bin/python # define the string that we will be working with s = 'I love Tutorial Arena so much' print s[2:] # from 2nd character to end print s[:6] # from beginning to the (6-1)th character print s[7:15] # from 7th to (15-1)th character print s[-4:] # 4 characters from the end to the end
If we were to run that script, we would get the following output:
So basically, we can specify what character to start at, what character to end at, or both. If we specify only the character to start at, the substring will go all the way to the end of the string and vice versa.
Note that a colon ( : ) is used to separate the starting and ending position. If we omit either the starting or ending position, the starting position would be taken to be the beginning of the string if the omission came before the colon, or the ending position would be taken as the end of the string if the omission came after the colon.
If we use negative numbers, it will be treated as that many characters from the end of the string. So if we had -5, that would be 5 characters from the end of the string. In other words, the last character in the string is treated as -1.
Also, it is of utmost importance that you remember that the first character in a string is treated as character zero (0). This is how it is treated in a vast number of programming languages and Python is no different.
Look at the example again to reinforce what you have learned. Play with it and see if you get the changes that you expect.
And that is it for Python substrings. We hope this tutorial was helpful.