Subscript Operator
In Python, the subscript operator (square brackets []
) is used to access individual characters or
substrings within a string.
Accessing Individual Characters
You can access a specific character in a string by providing its index within square brackets. Indexing starts at 0 for the first character.
Python
my_string =
"Hello, world!"
first_character = my_string[
0]
# Output: 'H'
Slicing Strings
To extract a substring, you can use slicing with the subscript
operator. The syntax is string[start:end:step]
:
· start: The starting index (inclusive).
· end: The ending index (exclusive).
· step: The step size (default is 1).
Python
my_string =
"Hello, world!"
substring = my_string[
2:
5]
# Output: 'llo'
Negative Indexing
You can use negative indices to access characters from the end of the string:
Python
my_string =
"Hello, world!"
last_character = my_string[-
1]
# Output: '!'
Key Points
· Strings are immutable, meaning you cannot change individual characters using the subscript operator.
· The index must be within the valid range of the string length.
· Slicing creates a new string without modifying the original.
By understanding the string subscript operator, you can effectively manipulate and extract information from strings in your Python code.