Skip to content

Indexing String: Mastering Efficiently


String Indexing in Python

Strings in Python are ordered sequences of character data. Indexing allows you to access individual characters in a string directly by using a numeric value. In Python, string indexing is zero-based: the first character in the string has an index of 0, the next character has an index of 1, and so on.

To demonstrate string indexing, let’s consider the string ‘mybacon’:

s = 'mybacon'
print(s[0]) # Output: 'm'
print(s[1]) # Output: 'y'
print(s[6]) # Output: 'n'

You can also use negative indices to access characters from the end of the string:

print(s[-1]) # Output: 'n'
print(s[-4]) # Output: 'a'
print(s[-len(s)]) # Output: 'm'
print(s[-7]) # Output: 'm'

If you try to access an index that is out of range, such as s[7], it will result in an error: IndexError: string index out of range. In the same way, if you try to access an empty string, such as t = '', and try to access the first index t[0], you will also get an IndexError because the index is out of range.

It’s important to note that the index of the last character in a string is always len(s) - 1. In our example, len(s) is 7, so the last character ‘n’ can be accessed using s[len(s) - 1] or simply s[6].

String Slicing

In addition to accessing individual characters, you can also extract a range of characters from a string using string slicing. String slicing allows you to create a new string that includes a subset of the original string.

The syntax for string slicing is [start:end:step], where start is the starting index (inclusive), end is the ending index (exclusive), and step is the number of characters to skip. If any of these parameters is omitted, it will use default values: 0 for start, len(s) for end, and 1 for step.

Let’s take a look at some examples:

s = 'mybacon'
print(s[1:4]) # Output: 'yba'
print(s[:5]) # Output: 'mybac'
print(s[2:]) # Output: 'bacon'
print(s[1:6:2]) # Output: 'ybco'

In the first example, s[1:4] returns a new string that includes characters from index 1 to index 3. The second example, s[:5], returns a new string that includes characters from the beginning of the string up to index 4. The third example, s[2:], returns a new string that includes characters from index 2 to the end of the string. Finally, s[1:6:2] returns a new string that includes characters from index 1 to index 5 with a step of 2.

String slicing can be a powerful tool for manipulating and extracting substrings from a larger string.

By understanding string indexing and string slicing, you now have the ability to retrieve and manipulate individual characters and substrings from strings in Python. This knowledge will be helpful when working with text data and performing various string operations in your Python programs.