In this article, we will see how to get a substring of a string in Python.
Python strings are sequences of individual characters. Python calls the concept “slicing” to get substring of Python string. Indexing starts from 0 to n-1(length of string -1).
Python Slice Notation:
a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array
There is also the step value, which can be used with any of the above:
a[start:stop:step] # start through not past stop, by step
Python substring examples:
str="Welcome to r2schools" print(str[2:]) #It displays the string from position 3 print(str[3:9]) #Displays the string from position 4 to 9. But, not 10th character print(str[-2:]) #displays from the last but one character onwards print(str[2:-2]) # displays from 3rd postion to last but one position
Output: