str="JAVATPOINT"
print("str is:",str)
print("str[0] is:",str[0])
print(" ")
print(" ")
print("str[1] is:",str[1])
print(" ")
print(" ")
print("str[2] is:",str[2])
print(" ")
print(" ")
print("str[3] is:",str[3])
print(" ")
print(" ")
print("str[4] is:",str[4])
print(" ")
print(" ")
print("str[9] is:",str[9])
print(" ")
print(" ")
print("str[12] is:",str[12])
print(" ")
print(" ")
# It returns the IndexError because 6th index doesn't exist
output:
str is: JAVATPOINT
str[0] is: J
str[1] is: A
str[2] is: V
str[3] is: A
str[4] is: T
str[9] is: T
Traceback (most recent call last):
File "C:/Users/mhtpr/Documents/FormatFactory/string.py", line 61, in <module>
print("str[12] is:",str[12])
IndexError: string index out of range
========================================================================
the slice operator [] is used to access the individual characters of the string.
# Start Oth index to end
print("str[0:] is:",str[0:])
print(" ")
print(" ")
# Starts 1th index to 4th index
print("str[1:5] is:",str[1:5])
print(" ")
print(" ")
# Starts 2nd index to 3rd index
print("str[2:4] is:",str[2:4])
print(" ")
print(" ")
# Starts 0th to 2nd index
print("str[:3] is:",str[:3])
print(" ")
print(" ")
#Starts 4th to 6th index
print("str[4:7] is:",str[4:7])
print(" ")
print(" ")
Output:
str[0:] is: JAVATPOINT
str[1:5] is: AVAT
str[2:4] is: VA
str[:3] is: JAV
str[4:7] is: TPO
========================================================================
negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The second rightmost index indicates -2,
str="JAVATPOINT"
print("str is:",str)
print("str[-1] is:",str[-1])
print(" ")
print(" ")
print("str[-3] is:",str[-3])
print(" ")
print(" ")
print("str[-2:] is:",str[-2:])
print(" ")
print(" ")
print("str[-4:-1] is:",str[-4:-1])
print(" ")
print(" ")
print("str[-7:-2] is:",str[-7:-2])
print(" ")
print(" ")
# Reversing the given string
print("str[::-1] is:",str[::-1])
print(" ")
print(" ")
print("str[-12] is:",str[-12])
print(" ")
print(" ")
Output:
str is: JAVATPOINT
str[-1] is: T
str[-3] is: I
str[-2:] is: NT
str[-4:-1] is: OIN
str[-7:-2] is: ATPOI
str[::-1] is: TNIOPTAVAJ
Traceback (most recent call last):
File "C:/Users/mhtpr/Documents/FormatFactory/string.py", line 32, in <module>
print("str[-12] is:",str[-12])
IndexError: string index out of range