We can extract subsets of strings by using the slice operator ([] and [:]). We need to specify the index or the range of characters to be extracted. Actually, 0 is the index of the first character, and n-1 is the character of the last element, where n is the number of characters in the string.
When we want to extract characters starting from the end of the string, then we must specify the index as a negative number. For example, the index of the last character is -1.
Python Slice String Example
a="Python is easy to learn and easy to understand" print(a) # Prints all characters print(a[0]) # Prints 1st character print(a[1:3]) # Prints characters starting from 2nd character to 3rd character print(a[4:]) # Prints characters starting from 5th character print(a[-1]) # Prints last character print(a[:5]) # Prints characters starting from first character to 5th character
Output:
Python is easy to learn and easy to understand P yt on is easy to learn and easy to understand d Pytho
Leave a comment