[]
). For example:my_string = "Hello, World!"
print(my_string[0]) # Outputs: H
print(my_string[-1]) # Outputs: !
-1
represents the last character.my_string = "Python is awesome!"
# Extract the first four characters
print(my_string[:4]) # Outputs: Python
# Get the third and fourth characters
print(my_string[2:5]) # Outputs: tho
string[start:end]
. If the start index is not specified, it defaults to 0, and if the end index is not provided, it defaults to the length of the string.my_string[-5:]
would extract the last five characters.What causes it: Accessing an index that is out of bounds (greater than or equal to the length of the string).
my_string = "Hello, World!"
print(my_string[15]) # Outputs: IndexError: string index out of range
Error message:
Traceback (most recent call last):
File "example.py", line 3, in <module>
print(my_string[15])
IndexError: string index out of range
Solution: Use a valid index within the bounds of the string.
print(my_string[-6]) # Outputs: !
Why it happens: The specified index is greater than or equal to the length of the string.
How to prevent it: Ensure that the index you're accessing falls within the bounds of the string (0 to length-1
).
What causes it: Trying to perform an operation on a string that is not supported, such as using arithmetic operators.
my_string = "Hello"
print(my_string + 5) # Outputs: TypeError: can't convert 'int' to str
Error message:
Traceback (most recent call last):
File "example.py", line 3, in <module>
print(my_string + 5)
TypeError: can't convert 'int' to str
Solution: Convert the integer to a string before performing the operation or use an appropriate operator for strings.
print("Length of string is: " + str(len(my_string))) # Outputs: Length of string is: 5
Why it happens: Trying to perform an operation that requires both operands to be of the same type, but one operand is a string and the other is not.
How to prevent it: Ensure that both operands are of the same type or use appropriate operators for strings.
find()
, rfind()
, or split()
in some cases for better performance.string[start:end]
.