Python Strings With Examples
What are Strings in Python?
In Python, strings are byte arrays that represent Unicode characters. Because of the lack of a character data type in Python, a single character is just a one-length string. To access the string's components, use square brackets.
How to Access Characters or Elements From a String in Python?
Using indexing, you can access specific characters. On the other hand, you can use slicing to access a group of characters. The index starts from zero.
You'll get an IndexError if you try to access a character outside of the index range. As the index, an integer must be used. We can't use floating or other types since we'll get a TypeError.
Negative indexing is supported by Python sequences. Here, it represents the last item by -1, the second-last item by -2, and the list goes on. You can use the slicing operator (:) to access the list of things in a string.
#Accessing string characters in Python str = 'wscube' print('str = ', str) #first character print('str = ', str) #last character print('str[-1] = ', str[-1]) #slicing 2nd to 5th character print('str[1:5] = ', str[1:5])