Python Strings

String indexing and slicing

1. Accessing individual characters:

Python strings behave like sequences, where each character has a designated position or index. You can access any character in a string using its index within square brackets []. Indexing starts from 0, meaning the first character has index 0, the second character has index 1, and so on.

Example:

my_string = "Hello, world!"

# Accessing the first character
first_char = my_string[0]  # H
print("The first character is:", first_char) 

# Accessing the last character
last_char = my_string[-1]  # ! (notice negative indexing)
print("The last character is:", last_char)


2. String slicing:

String slicing allows you to extract a portion (substring) of a string based on a starting and ending index. You use square brackets [] with a colon : separating the start and end indices. Here's the key point:

The end index is exclusive, meaning the character at that index is not included in the substring.

my_string = "Hello, world!"
sub_string = my_string[2:7]  # llo, Wor  (extracts characters from index 2 to 6 (exclusive))
print("Substring between index 2 and 6:", sub_string)

In this example, sub_string captures characters from index 2 (inclusive) to index 6 (exclusive), resulting in "llo, Wor".


3. Negative indexing:

Python also supports negative indexing, which allows you to access characters from the end of the string. The index -1 refers to the last character, -2 refers to the second-last character, and so on.

my_string = "Hello, world!"
second_last_char = my_string[-2]  # r (accessing from the right)
print("The second last character:", second_last_char) 

# Extracting from the 5th character from the end (world!)
from_end = my_string[-5:]
print("Substring starting from the 5th character from the end:", from_end)

Here, second_last_char retrieves the character at index -2, which is "r". Similarly, from_end extracts characters from the 5th character from the end (index -5) to the end of the string, resulting in "world!".

It's time to take a quiz!

Test your knowledge and see what you've just learned.

How do you access the first character of a string in Python?

my_string[0]
my_string[-1]
my_string[1]
Check Answer

What is the result of my_string[2:7] for my_string = "Hello, world!"?

"lo, wo"
"llo, "
"Hel"
Check Answer

Which character is accessed with my_string[-2] if my_string = "Hello, world!"?

"r"
"!"
"d"
Check Answer

What does my_string[-5:] return for my_string = "Hello, world!"?

"world!"
"Hello"
"rld!"
Check Answer

What is the key rule of string slicing when specifying the start and end index?

The start index is exclusive.
The end index is inclusive.
The end index is exclusive.
Check Answer